claydiffrient
claydiffrient

Reputation: 1306

Multiple reads from multiple C++ sockets

I'm working to implement a server for a Rock Paper Scissors protocol. So far things are going really well except I have one snag I'm trying to get past. As a total overview of the program:

  1. A client connects to the server.
  2. A second client connects to the server.
  3. The server receives input from client 1.
  4. The server receives input from client 2.
  5. The server determines a winner then sends back winning information to each client.

I've wrapped the sockets in a class to allow an easier API for working with them. The part that I'm having trouble with is here:

  char playerOneRequest;
  char playerTwoRequest;
  int playerOneLength = mPlayerOne->receive(&playerOneRequest,
                                            BUFFER_SIZE);
  cerr << "After player one\n";
  cout << "Received '" << playerOneRequest << "' from player one.\n";
  int playerTwoLength = mPlayerTwo->receive(&playerTwoRequest,
                                            BUFFER_SIZE);
  cerr << "After player two\n";
  cerr << "Received '" << playerTwoRequest << "' from player two.\n";

  char playerOne = toupper(playerOneRequest);
  char playerTwo = toupper(playerTwoRequest);

I've been using DDD to debug it and I've discovered a problem. Let's imagine that player one sent a R and player two sent a S. After the first receive playerOneRequest is R after the second receive which is to player two (a separate TCP stream) playerTwoRequest is S. But at this point playerOneRequest now equals \r.

I can't figure out why this is the case. All my code is available in this Gist

Upvotes: 0

Views: 104

Answers (1)

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10415

What value is BUFFER_SIZE? You only have room for one character in playerOneRequest but it appears you may read more than one character from receive. Any additional characters read will be put into adjacent variables.

Upvotes: 2

Related Questions