Improve both client and server code to account for END of messages, allowing for incomplete packets with TCP

This commit is contained in:
mdiluzio 2015-01-03 18:55:44 +00:00
parent b34b933dcd
commit 18cfcff264
2 changed files with 29 additions and 15 deletions

View file

@ -101,17 +101,23 @@ int runClient(int argc, char* argv[])
while ( n >= 0 ) while ( n >= 0 )
{ {
memset(buffer,0,sizeof(buffer));
std::cout<<"Waiting for gamestate"<<std::endl; std::cout<<"Waiting for gamestate"<<std::endl;
// Receive gamestate
if (read(sockfd,buffer,sizeof(buffer)-1) < 0)
error("ERROR reading from client");
std::cout<<buffer<<std::endl; std::string gamestate;
while( gamestate.find("END") == std::string::npos )
{
// Receive gamestate
memset(buffer,0,sizeof(buffer));
if (read(sockfd,buffer,sizeof(buffer)-1) < 0)
error("ERROR reading from client");
gamestate+=buffer;
}
std::cout<<gamestate<<std::endl;
// Output orders // Output orders
std::string orders = std::to_string(sockfd); std::string orders = "END";
std::cout<<"Sending orders"<<std::endl; std::cout<<"Sending orders"<<std::endl;
std::cout<<orders<<std::endl; std::cout<<orders<<std::endl;

View file

@ -11,21 +11,29 @@
int WaitForOrdersFromClient(const ClientInfo info, std::mutex &mut, CTTRTSGame &game) int WaitForOrdersFromClient(const ClientInfo info, std::mutex &mut, CTTRTSGame &game)
{ {
char buffer[1028]; // buffer for orders char buffer[1028]; // buffer for orders
memset(buffer,0,sizeof(buffer));
std::cout<<"Waiting for "<<inet_ntoa(info.cli_addr.sin_addr)<<std::endl; std::cout<<"Waiting for "<<inet_ntoa(info.cli_addr.sin_addr)<<std::endl;
// Read in the new socket std::string orders;
// read will block until the client has called write
// up to the full size of the buffer while ( orders.find("END") == std::string::npos )
if (read(info.clientsockfd,buffer,sizeof(buffer)-1) < 0) {
error("ERROR reading from client"); memset(buffer,0,sizeof(buffer));
// Read in the new socket
// read will block until the client has called write
// up to the full size of the buffer
if (read(info.clientsockfd,buffer,sizeof(buffer)-1) < 0)
error("ERROR reading from client");
// Append the received orders
orders+=buffer;
}
std::cout<<"Recieved orders from "<<inet_ntoa(info.cli_addr.sin_addr)<<std::endl; std::cout<<"Recieved orders from "<<inet_ntoa(info.cli_addr.sin_addr)<<std::endl;
std::cout<<buffer<<std::endl;
mut.lock(); mut.lock();
game.IssueOrders(info.player , buffer); game.IssueOrders(info.player , orders);
mut.unlock(); mut.unlock();
return 0; return 0;