Reputation: 121
So my problem is that when I use WinSock "send" in my do-while loop, PUTTY receives it twice.
char sendBuffer[] = "this is my message to the world";
do
{
iResult = recv(clientSocket, recvBuffer, DEFAULTBUFFERLEN, 0);
if(iResult > 0)
{
std::cout << "Received bytes: " << iResult << std::endl;
std::cout << recvBuffer << std::endl;
//Successful receive, now send back a message
Message("Now it's your turn to say something!");
//std::cin.getline(sendBuffer, DEFAULTBUFFERLEN);
std::cin.get();
iSendResult = send(clientSocket, sendBuffer, sizeof(sendBuffer), 0);
if(iSendResult == SOCKET_ERROR)
{
Message("Error with send. ERROR: " + WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
return 8;
}
std::cout << "Bytes sent: " << iSendResult << std::endl;
}
else if(iResult == 0)
{//Nothing has been received, client has disconnected
Message("Closing connection with client");
}else
{// there was an errror and the connection needs to be closed
Message("Error Receiving. Error: " + WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
return 9;
}
}while(iResult > 0);
The code works otherwise works well, compiles and overall, goes smoothly, the only problem is that the send call sends it twice for some reason.
I call send once before this only to say "Welcome to the server" but that actually only sends once. It's only the one in this bit that sends twice. I'm using mingw to compile and this is my build script
g++ server.cpp -o server -lws2_32 -lwsock32
Edit: According to my debugger, the code runs once when it receives an initial message from the client but then runs again and is receiving "\r\n" when it runs again, hence the repeated message without waiting for a new client message
Upvotes: 0
Views: 625
Reputation: 121
So after some debugging I found out the problem, putty sends a an extra message when you press enter(or something to this effect. So the solution was to wrap the code handling received messages with an if statement with these conditions:
if((std::string)recvBuffer != "\r\n" || (std::string)recvBuffer != "\n")
Upvotes: 1