Socket Programming recv function

Hello, anyone familiar with Socket Programming how come I cannot do this on the client side ?

the first time the recv function works but the second time it hangs up.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

        char * recvbuf = new char[32]; 

        int bytesRecv = recv(hSocket, recvbuf, 32, 0);

	cout << "Recv = " << bytesRecv << ": " << recvbuf << endl;
	

	char * recvbuf2 = new char[32];

	int bytesRecv2 = recv(hSocket, recvbuf2, 32, 0);

        cout << "Recv = " << bytesRecv2 << ": " << recvbuf2 << endl;

How many bytes did you send?

What did the first recv cout print?

Note that recv does NOT append a \0 to make whatever you received a printable string.

So
1
2
3
4
5
6
char * recvbuf = new char[32]; 
int bytesRecv = recv(hSocket, recvbuf, 31, 0);  // leave space for a \0 to be added
if ( bytesRecv > 0 ) {
    recvbuf[bytesRecv] = '\0';
    cout << "Recv = " << bytesRecv << ": " << recvbuf << endl;
}

or
1
2
3
4
5
6
char * recvbuf = new char[32]; 
int bytesRecv = recv(hSocket, recvbuf, 32, 0);
if ( bytesRecv > 0 ) {
   string s(recvbuf,bytesRecv);
   cout << "Recv = " << bytesRecv << ": " << s << endl;
}


Also for TCP (aka stream) connections, the only guarantee is byte ordering. Sending "hello" does not guarantee "hello" as the result of a single recv call. You might get each letter separately.

https://blogs.msdn.microsoft.com/joncole/2006/03/20/simple-message-framing-sample-for-tcp-socket/

Topic archived. No new replies allowed.