In C# (a Unity script), I have a client that uses either an TcpClient to send and receive data. The client will send a fixed data string every "frame" to the server. The server just echoes back that same string. This is testing and simulation purposes.
I use the Async methods BeginWrite and BeginReceive. The data is sent by the client by using:
stream.BeginWrite(data, 0, data.Length, new AsyncCallback(EndTCPSend), null);
And I use the following call to receive data:
TCPClient.GetStream().BeginRead(TCPBuffer, 0, 1024, new AsyncCallback(OnMessageTCP), null);
Now, the problem is that after a short period of time (1 second or so) the client stops sending out data to the server, even though the code that calls the method for sending is still being called (verified through log output and Wireshark). No data is send out, and thus no data is received anymore at the server.
The following code is used to initialize the TcpClient:
TCPClient = new TcpClient();
TCPClient.NoDelay = true;
TCPClient.Connect(remoteEndPoint);
if (TCPClient.GetStream().CanRead)
{
TCPClient.GetStream().BeginRead(TCPBuffer, 0, 1024, new AsyncCallback(OnMessageTCP), null);
}
Every frame, the following code is used to start sending the string:
NetworkStream stream = TCPClient.GetStream();
if (stream.CanWrite)
{
byte[] data = Encoding.UTF8.GetBytes(msg);
stream.BeginWrite(data, 0, data.Length, new AsyncCallback(EndTCPSend), null);
}
And the following method is used to close the async sending:
private void EndTCPSend(IAsyncResult result)
{
TCPClient.GetStream().EndWrite(result);
}
To receive the data, I use the following method as a callback:
private void OnMessageTCP(IAsyncResult result)
{
NetworkStream stream = TCPClient.GetStream();
int read = stream.EndRead(result);
if (read == 0)
{
return;
}
string message = Encoding.UTF8.GetString(TCPBuffer, 0, read);
TCPMessageBuffer += message; // <-- This line seems to cause the problem.
stream.BeginRead(TCPBuffer, 0, 1024, new AsyncCallback(OnMessageTCP), null);
}
Anyone any idea of what I do wrong here? Any reason why the client stops sending? Can I send and receive data asynchronously like that?
Thanks in advance!