tags:

views:

58

answers:

2

Hi to all,

I'm programming a very simple socket server following this sample code. The server is up and running and I can connect to it via telnet (using Putty, actually). Whenever a new connection is received, I spawn a new thread that is the following code:

DWORD WINAPI receive_cmds(LPVOID lpParam) 
{
      char outbuffer[100];
      outbuffer[0] = '\0';
      char inbuffer[100];
      inbuffer[0] = '\0';
      int res;
      SOCKET current_client = (SOCKET)lpParam;

      while (1) {           
          res = recv(current_client, inbuffer, sizeof inbuffer - 1, 0);
          if (res > 0) {
              inbuffer[res] = '\0';
              printf("Got '%s'\n", inbuffer);
          }              
          Sleep(10);

          if (res == 0) {
             closesocket(current_client);
             ExitThread(0);             
          }                          

          //printf("%s\n", inbuffer); 
          strcpy(inbuffer, "");
      }
}

As soon as I connect it prints this gibberish:

alt text

If i input "hello" and then "stackoverflow" in the client, this is what I get:

alt text

Even if I declared explicitly the end of line '\0', it seems to take much more of the line, plus I don't know why it prints the input two times, the second being the first one minus the first one or two characters.

Any help on understanding what is going on? Thanks in advance.

EDIT: edited accordingly to what suggested by unwind

A: 

I guess that recv() is returning "-1" (meaning error).

I'd have to see the rest of your code to guess why. Try testing for a return of -1 and then calling WSAGetLastError() to find out the reason for the error.

Michael J
hi! i tried and it doesn't return any error.
pistacchio
+3  A: 

You should do better error-checking, and more sensible buffer handling:

res = recv(current_client, inbuffer, sizeof(inbuffer), 0);

should be

res = recv(current_client, inbuffer, sizeof inbuffer - 1, 0);
if (res > 0)
{
  inbuffer[res] = '\0';
  printf("Got '%s'\n", inbuffer);
}

You need to leave space in the buffer for the terminator, so you can't use all of the buffer to receive data. And you should check for -1, and terminate the buffer to make it into a string before printing it as such.

unwind
Hi! thank you very much, I'm getting way closer now. As soon as i connect I still get "Got <GIBBERISH>" and the double input problem, the second being a '\n', i guess
pistacchio
What's the value of `res`?
Alok
@Alok: the man page for recv says: "recv() returns the number of bytes received, or -1 if an error occurred" (slighly paraphrased for grammar).
unwind
@unwind: sorry about my comment, it was meant for @pistacchio - I was trying to see why he still got gibberish after making the changes suggested by you.
Alok