I'm pretty new to network programing. I've written a simple non-blocking TCP Server using winsock2 but it behaves in a weird way that I couldn't find any example of it in previously asked questions.
My server can only send a message with as many bytes as it previously received. For example, if previously it received a "rec_msg", when I try to send "message_to_send" it only sends "message".
I don't if it has any effect but the server is encapsulated with a pure static class. Here are the function via a recieve and send message:
int TCPServer_Test::receiveMessage(){
while(1)
{
memset(recvbuf, 0, DEFAULT_BUFLEN);
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
int err = WSAGetLastError();
int counter = 0;
if (iResult > 0)
{
std::cout << "Mesaj Alindi: " << recvbuf << std::endl;
break;
}
else if(err == WSAEWOULDBLOCK)
{
Sleep(200);
continue;
}
else if (iResult == 0){
printf("Connection closing...\n");
return -1;
}
else
{
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
assert(false);
}
}
}
void TCPServer_Test::sendMessage(char* Source){
strncpy(recvbuf, Source, DEFAULT_BUFLEN);
iSendResult = send( ClientSocket, recvbuf, iResult, 0);
if (iSendResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
assert(false);
}
else if (iSendResult == 0) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
assert(false);
}
else
{
printf("Bytes sent: %d\n", iSendResult);
}
memset(recvbuf, 0, sizeof(recvbuf));
}
I would appreciate any help directly related or not.
It looks like it happens because you are using
iResult
variable that contains amount of data received during previousrecv
call when sending data instead of supplying real size of the data to be sent like this:Also notice that there is no real need to copy data into buffer.