来自 TCPClient 的流从下一个数据包中捕获数据 [英] Stream from TCPClient catching data from next packet
问题描述
我正在开发一些通过 TCP 侦听来自另一个程序的事件的软件.
I'm developing some software that listens for events from another program via TCP.
事件以字符串形式出现,格式如下:value1;value2;value3"问题是有时 value1 中的单个字符会被读取到前一个事件中,所以我会得到这样的信息:
The events come in a string formatted like this: "value1;value2;value3" The problem is that sometimes a single character from value1 gets read onto the previous event so i get something like this:
value1;value2;value3v
value1;value2;value3v
alue1;value2;value3
alue1;value2;value3
如何让它知道每条消息的开始和结束位置?
How can i make it know where each message begins and ends?
代码如下:
Dim client As New TcpClient()
Sub listen()
Dim networkStream As Stream = client.GetStream()
While True
Dim bytes(client.ReceiveBufferSize) As Byte
Dim size As Integer = 0
size = networkStream.Read(bytes, 0, CInt(client.ReceiveBufferSize))
'process event here
End While
End Sub
这一切都是在它自己的线程上完成的.
This is all done on a thread of it's own.
推荐答案
发送方必须包含其发送的每个数据的长度,因此在接收方您将收到所提供的长度.更简单的选择是包含 NULL 终止,以便您可以在接收器端将其作为单独的字符串读取.
Sender has to included the length of each data its sending so at receiver you will receive upto the provided length. Easier option would be to include NULL termination so that you can read it as individual string at receiver end.
这篇关于来自 TCPClient 的流从下一个数据包中捕获数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!