Reading from a Socket

Discuss the development of new homebrew software, tools and libraries.

Moderators: cheriff, TyRaNiD

Post Reply
Jai_Guru
Posts: 12
Joined: Sun Aug 13, 2006 8:01 am

Reading from a Socket

Post by Jai_Guru »

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: Select all

                while(1) {
                    bzero(&buffer, sizeof(buffer));
                    n = read(sockfd,buffer,255);
                    printf("%d bytes read\n", n);
                    if &#40;n < 0&#41; 
                        printf&#40;"ERROR reading from socket"&#41;;
                    printf&#40;"%s\n",buffer&#41;;
                &#125;
For example, if y send something lilke "Hello PSP\n" the output on the PSP is something like:

Code: Select all

1 bytes read
H
9 bytes read
ello PSP
How can I receive all the data sent by the server together?
siberianstar
Posts: 70
Joined: Thu Jun 22, 2006 9:24 pm

Post by siberianstar »

Using 'read' the simplest way is to read each time a char

Code: Select all

char buffer&#91;max_size&#93;;
int offset = 0;
char ch;
..
if &#40;read&#40;sockfd, &ch, 1&#41; < 0&#41; .. error, close socket ..
if &#40;ch == '\n'&#41;
&#123;
  buffer&#91;offset&#93; = 0; 
  offset = 0;
  parse_command&#40;buffer&#41;;
&#125;
else buffer&#91;offset++&#93; = ch;
..
but this will be slow, a faster way is to read buffer in chunk.
Jai_Guru
Posts: 12
Joined: Sun Aug 13, 2006 8:01 am

Post by Jai_Guru »

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' ?
Post Reply