void processIncomingData(receiveState currentState) { Program.logToWindow("Processing received data. New data: " + currentState.IsNewData + " Bytes read: " + currentState.bytesRead); if (currentState.IsNewData) //we have new data { currentState.receivedString.Append(Encoding.ASCII.GetString(currentState.dataReceived, 0, currentState.bytesRead)); string currentMessage = currentState.receivedString.ToString(); Program.logToWindow("We have new data. Current message: " + currentMessage); //If the amount of data read is >= the max buffer size, we should check for more if (currentState.bytesRead >= currentState.bufferSizeReadable) ipgnPugInterfaceSocket.BeginReceive(currentState.dataReceived, 0, currentState.bufferSizeReadable, SocketFlags.None, new AsyncCallback(receiveCallback), currentState); else { reactToBot(currentMessage); receiveBotCommand(); //start listening again } } else if (currentState.bytesRead > 0) { //Do something with the data we've got, because there's no more coming immediately Program.logToWindow("Received a command or a response from the pug bot"); string receivedMessage = currentState.receivedString.ToString(); Program.logToWindow("Received data: " + receivedMessage); //parse this command and react, sending the current status object with it reactToBot(receivedMessage); //go back to listening again receiveBotCommand(); } else { //let's presume it was closed... because this is what happens when it's closed onSocketError(ConnectionClosed); } }
public void receiveBotCommand() { try { receiveState currentState = new receiveState(); currentState.IsNewData = false; currentState.dataReceived = new byte[256]; ipgnPugInterfaceSocket.BeginReceive(currentState.dataReceived, 0, currentState.bufferSizeReadable, SocketFlags.None, new AsyncCallback(receiveCallback), currentState); } catch (SocketException) { onSocketError(ConnectionClosed); } }