首页 > 解决方案 > c# TCP socket没有收到消息

问题描述

我是 c# 中的套接字新手,在我的代码中看不到问题。我有一个 C++ 应用程序,当我的 C# 应用程序连接到它的套接字时,它会发送一系列 8 条消息。我知道 c++ 应用程序可以工作,因为它已经在其他地方进行了测试。

这是我的 c# 套接字创建代码

m_tcpESSClient = new TcpClient(AddressFamily.InterNetwork);
m_tcpESSClient.ReceiveBufferSize = 4096;
m_tcpESSClient.BeginConnect(
IPAddress.Parse("127.0.0.01"),
8082,
new AsyncCallback(ConnectCallback2),
m_tcpESSClient);

这是连接回调

private void ConnectCallback2(IAsyncResult result)
{
    m_tcpESSClient.EndConnect(result);
    State state = new State();
    state.buffer = new byte[m_tcpESSClient.ReceiveBufferSize];
    state.offset = 0;

    NetworkStream networkStream = m_tcpESSClient.GetStream();
            networkStream.BeginRead(
              state.buffer,
              state.offset,
              state.buffer.Length,
              ReadCallback2,
              state
              );
}

这是读取回调

private void ReadCallback2(IAsyncResult result)
{            
NetworkStream networkStream = m_tcpESSClient.GetStream();
int byteCount = networkStream.EndRead(result);

State state = result.AsyncState as State;
state.offset += byteCount;

// Show message received on UI
Dispatcher.Invoke(() =>
{                
    ListBox.Items.Add("Received ");
});

state.offset = 0;
networkStream.BeginRead(
state.buffer,
state.offset,
state.buffer.Length,
ReadCallback2,
state);

问题是没有收到 c++ 应用程序发送的所有消息。请任何人都可以看到我的套接字代码有什么问题。

标签: c#socketstcpclient

解决方案


TCP 没有消息的概念。TCP 对流进行操作。

这意味着即使 C++ 应用程序可能发出 8 个单独Write的调用,您也可能会通过一个单一的方法接收所有这些数据Read(或者需要多个Reads 来读取由一个单一的 s 写入的数据Write)。您添加到列表框中的项目与 C++ 应用程序发送给您的“消息”数量无关。

要真正识别单个消息,您需要在 TCP 流之上有一个基于消息的协议。你不能只依赖个人Read。在任何情况下,您都需要解析通过套接字接收到的数据。


推荐阅读