c# - 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++ 应用程序发送的所有消息。请任何人都可以看到我的套接字代码有什么问题。
解决方案
TCP 没有消息的概念。TCP 对流进行操作。
这意味着即使 C++ 应用程序可能发出 8 个单独Write
的调用,您也可能会通过一个单一的方法接收所有这些数据Read
(或者需要多个Read
s 来读取由一个单一的 s 写入的数据Write
)。您添加到列表框中的项目与 C++ 应用程序发送给您的“消息”数量无关。
要真正识别单个消息,您需要在 TCP 流之上有一个基于消息的协议。你不能只依赖个人Read
。在任何情况下,您都需要解析通过套接字接收到的数据。
推荐阅读
- python - 我应该怎么做才能在 Heroku 上使用 python-magic?
- linux-kernel - 进程控制块的文件格式是什么?
- qt - 如何更改 vlc-qt 媒体显示小部件?
- c# - 如何在 WinForms 中使用 GraphicsPath 填充不同颜色的椭圆?
- google-maps - Googlemaps 中的图像生成器
- jquery - 使用 jquery 从 umbraco 表单中获取变量
- jupyter - 在 Google Colab jupyter notebooks 中为动态生成的文件创建文件下载链接
- angular - 第二次没有在离子中调用函数
- c# - 将 Linq 查询转换为表达式树
- polymorphism - 多态列表和指针