Tcpclient不会在完成之前等待数据到达 [英] Tcpclient doesn't wait for data to arrive before completing
问题描述
好的,所以我不是专家或任何接近的人。我在VB中写作业余爱好,并编写了大量的小应用程序,其中大部分用于旧的串行设备连接。
现在这些设备通过TCP连接。很容易,所以我想...
我的服务器是一个嵌入式SBC,其通信协议非常结构化。所有数据都以固定字符ETX(ChrW(3))终止。所以我应该能够获得传入的响应流并将其保存到字符串,直到ETX到达。
这也是一个单击按钮,connect-send-receive sub。
有一个单独的连接/断开按钮会很有帮助,因为有时会发送多个命令并且重复连接/断开连接看起来很荒谬。
任何帮助都会很棒。
Kevin
Ok, So I'm not an expert or anywhere close. I write in VB as a hobby and have written plenty of small apps and the majority of them are for old serial device connections.
Now those devices are connecting via TCP. Easy, So I thought...
My server is a embedded SBC and very structured in its communication protocol. All data terminates with a fixed character ETX (ChrW(3)). So I should be able to get incoming response stream and save it to a string until the ETX arrives.
This also is a single click button, connect-send-receive sub.
Having a separate connect/disconnect button would be helpful as sometime multiple commands would be sent and connecting/disconnecting repeatedly seems ridiculous.
Any help would be great.
Kevin
Shared Sub Connect(server As [String], port as [Int32], message As [String])
Try
Dim client As New TcpClient(server, port)
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
Dim stream As NetworkStream = client.GetStream()
stream.Write(data, 0, data.Length)
RTB1_update("Sent: {0}", message)
data = New [Byte](256) {}
Dim responseData As [String] = [String].Empty
Threading.thread.sleep(2000)
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
RTB1_update("Received: {0}", responseData)
stream.Close()
client.Close()
Catch e As ArgumentNullException
RTB1_update("ArgumentNullException: {0}", e)
Catch e As SocketException
RTB1_update("SocketException: {0}", e)
End Try
End Sub
我是什么尝试过:
无论我做什么都不能做到这一点,等待超时约90秒是一个笑话。下面的代码直接来自MSDN,并在数据到达之前很久就完成了。添加一个或两个thread.sleep会有所帮助,但有些数据很长并且会被剪裁,有些数据非常短,而且长时间不需要的等待很愚蠢,
What I have tried:
No matter what I do it fails to do this and waiting for a timeout approx 90 seconds is a joke. The code below is straight off of MSDN and completes long before the data even arrives. Adding a thread.sleep for a second or two helps, but some data is long and gets clipped, some is very short and the long unneeded wait is silly,
推荐答案
您在代码中做出了无效的假设。请参阅 NetworkStream.Read方法(字节[] ,Int32,Int32)(System.Net.Sockets) [ ^ ],其中说明了read命令返回了多少(如果有的话)数据。不要假设您将在单个读取呼叫中接收所有数据。 TCP / IP与读取文件不同,因为您只能读取通过网络发送的任何内容,这可能一无所获。
You are making an invalid assumption in your code. See NetworkStream.Read Method (Byte[], Int32, Int32) (System.Net.Sockets)[^], where it explains how much (if any) data is returned on the read command. Do not assume that you will receive all the data on a single read call. TCP/IP is not like reading a file, as you can only read whatever has been sent across the network, which may be nothing.
这篇关于Tcpclient不会在完成之前等待数据到达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!