| View previous topic :: View next topic |
| Author |
Message |
Jai_Guru
Joined: 13 Aug 2006 Posts: 12
|
Posted: Sun Aug 13, 2006 8:11 am Post subject: Reading from a Socket |
|
|
I'm trying to create a client program that connects to a server on my computer.
When I try to receive on the PSP a string sent by the server I only receive one character at first and then the rest of the string.
This is the code I use:
| Code: |
while(1) {
bzero(&buffer, sizeof(buffer));
n = read(sockfd,buffer,255);
printf("%d bytes read\n", n);
if (n < 0)
printf("ERROR reading from socket");
printf("%s\n",buffer);
}
|
For example, if y send something lilke "Hello PSP\n" the output on the PSP is something like:
| Code: |
1 bytes read
H
9 bytes read
ello PSP
|
How can I receive all the data sent by the server together? |
|
| Back to top |
|
 |
siberianstar
Joined: 22 Jun 2006 Posts: 70
|
Posted: Sun Aug 13, 2006 9:42 am Post subject: |
|
|
Using 'read' the simplest way is to read each time a char
| Code: |
char buffer[max_size];
int offset = 0;
char ch;
..
if (read(sockfd, &ch, 1) < 0) .. error, close socket ..
if (ch == '\n')
{
buffer[offset] = 0;
offset = 0;
parse_command(buffer);
}
else buffer[offset++] = ch;
..
|
but this will be slow, a faster way is to read buffer in chunk. |
|
| Back to top |
|
 |
Jai_Guru
Joined: 13 Aug 2006 Posts: 12
|
Posted: Sun Aug 13, 2006 9:54 am Post subject: |
|
|
How can I read buffer in chunk?
When I try to do it, the string sent by the server is split as I explained on my first post.
What alternatives do I have other than using 'read' ? |
|
| Back to top |
|
 |
|