behaviour of sockets

I'm having trouble writing a chat program that is supposed to use sockets. Here is an excerpt of the client side code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void input(void *p){

	char buf[MAX_LINE];
	//while(buf!="exit"){	
		printf("Type whatever you want: ");
		scanf("%s", buf);
		send(s, buf, strlen(buf), 0); 
		scanf("");
	//}
}

void rec(void *p){

	char buf2[MAX_LINE];

	printf("buf===%s\n",buf2);
	//while(buf!="close"){
		int len = recv(s, buf2, MAX_LINE, 0);
		if(len<0){ printf("recv error!\n");}
		else{
			printf("num chars = %d\n",len);
			buf2[len] = 0;
			printf("Server says: %s\n", buf2);
			printf("%s",errno);
		}
	//}
}


For some reason, recv is returning instantly with -1. The main function of my program spawns a thread for the rec function and then calls the input function directly. The socket that both send and recv are using is a global variable.

Any ideas why recv is returning instantly with -1? The code on the server side is:

1
2
3
4
5
      	// Send and receive data.
         char buf[MAX_LINE];
         int len = recv( s, buf, MAX_LINE, 0 );
         buf[len] = 0;
         send( s, buf, strlen(buf), 0 );


And I know it works just fine. (expected behaviour is that it just sits there waiting for message from client, then obviously echoes it back.)

Thanks for your help in advance!
Are you error checking when you are trying to open the sockets etc? If you get a weird value (most return -1 or similar) you can call WSAGetLastError() to get what specifically went wrong. You can look up the return values at msdn.com, but most of them are self explanatory.
ok well, i'm not sure what's going on now because i'm not getting the same errors. I was getting an error telling me the stack around buf2 was corrupted each time. now it's working as expected. However, recv is returning instantly with 0. it should be blocking waiting for a message from the server but none is being sent so it should block forever... :( i'll have to fiddle some more
Make sure your entire program is not exiting too, that could be a possible cause (however unlikely).
Topic archived. No new replies allowed.