[英]c# TCP socket not receiving messages
I am new to sockets in c# and cannot see the problem in my code. 我是C#套接字的新手,无法在我的代码中看到问题。 I have a C++ app that sends a series of 8 messages when my C# application connects to its socket.
我有一个C ++应用程序,当我的C#应用程序连接到其套接字时,它会发送一系列8条消息。 I know that the c++ application works because it has been tested elsewhere.
我知道C ++应用程序可以工作,因为它已经在其他地方进行了测试。
This is my c# socket creation code 这是我的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);
This is the connect callback 这是连接回调
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
);
}
and this is the read callback 这是读取回调
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);
The problem is that all messages sent by the c++ application are not received. 问题是未收到c ++应用程序发送的所有消息。 Please can anyone see what is wrong with my socket code.
请任何人看看我的套接字代码有什么问题。
TCP doesn't have a concept of messages. TCP没有消息的概念。 TCP operates on streams.
TCP在流上运行。
This means that even though the C++ application might be issuing eight separate Write
calls, you might receive all of that data with a single Read
(or require multiple Read
s to read data written by a single Write
). 这意味着即使C ++应用程序可能发出八个单独的
Write
调用,您也可能会通过一个Read
接收所有数据(或者需要多个Read
来读取单个Write
写入的数据)。 The items you add to the list box have no relation to the amount of "messages" the C++ application has sent you. 您添加到列表框中的项目与C ++应用程序发送给您的“消息”的数量无关。
To actually identify individual messages, you need to have a message-based protocol on top of TCP streams. 要真正识别单个消息,您需要在TCP流之上具有基于消息的协议。 You can't just rely on individual
Read
s. 您不能仅仅依靠单个
Read
。 In any case, you need to parse the data you receive over the socket. 无论如何,您都需要解析通过套接字接收的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.