C#TcpClient:意外停止发送

时间:2014-07-06 16:22:13

标签: c# tcpclient beginread

在C#(Unity脚本)中,我有一个使用TcpClient发送和接收数据的客户端。客户端将每个“帧”发送一个固定数据字符串到服务器。服务器只回显相同的字符串。这是测试和模拟的目的。

我使用Async方法BeginWrite和BeginReceive。客户使用以下方式发送数据:

stream.BeginWrite(data, 0, data.Length, new AsyncCallback(EndTCPSend), null);

我使用以下调用来接收数据:

TCPClient.GetStream().BeginRead(TCPBuffer, 0, 1024, new AsyncCallback(OnMessageTCP), null);

现在,问题是在很短的一段时间(大约1秒钟)之后,客户端停止向服务器发送数据,即使仍在调用调用发送方法的代码(通过日志输出验证)和Wireshark)。没有数据被发送出去,因此服务器上不再接收任何数据。

以下代码用于初始化TcpClient:

TCPClient = new TcpClient();
TCPClient.NoDelay = true;
TCPClient.Connect(remoteEndPoint);
if (TCPClient.GetStream().CanRead)
{
    TCPClient.GetStream().BeginRead(TCPBuffer, 0, 1024, new AsyncCallback(OnMessageTCP), null);
}

每一帧,以下代码用于开始发送字符串:

NetworkStream stream = TCPClient.GetStream();
if (stream.CanWrite)
{
    byte[] data = Encoding.UTF8.GetBytes(msg);
    stream.BeginWrite(data, 0, data.Length, new AsyncCallback(EndTCPSend), null);
}

以下方法用于关闭异步发送:

private void EndTCPSend(IAsyncResult result)
{
    TCPClient.GetStream().EndWrite(result);
}

要接收数据,我使用以下方法作为回调:

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);
}

任何人都知道我在这里做错了什么?客户端停止发送的原因是什么?我可以像这样异步发送和接收数据吗?

提前致谢!

0 个答案:

没有答案