gpt4 book ai didi

vb.net - 在 VB.NET 中通过 TCP/IP 发送数据时程序卡住

转载 作者:可可西里 更新时间:2023-11-01 02:54:06 32 4
gpt4 key购买 nike

我有一个程序正在向服务器发送数据,但它在尝试发送数据时死机了。

  Dim postData = "000000001119001  MY0121     020216081825S0000000001233300000000002050"
Dim client As New TcpClient(IPAddressTextbox.Text, 17476)

' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(postData)

' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
Dim stream As NetworkStream = client.GetStream()

' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)

Console.WriteLine("Sent: {0}", postData)

' Receive the TcpServer.response.
' Buffer to store the response bytes.

data = New [Byte](256) {}

' String to store the response ASCII representation.
Dim responseData As [String] = [String].Empty

' Read the first batch of the TcpServer response bytes.
Dim bytes As Int32 = stream.Read(data, 0, data.Length)

responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)

Console.WriteLine("Received: {0}", responseData)
ResponseBox.Text = responseData
' Close everything.
stream.Close()
client.Close()

我做了一些故障排除,发现它卡住在这一行

Dim bytes As Int32 = stream.Read(data, 0, data.Length)

我从Here得到这一段代码因为我刚刚开始学习 TCP 连接,并且认为 Microsoft 可能是一个很好的学习资源。我已验证服务器 IP 和端口有效并接受我的连接。

最佳答案

figured Microsoft may be a good resource to learn from

哈哈哈... :( MSDN 套接字代码是找到的最糟糕的套接字代码之一。

如果读取“挂起”,这意味着远程端甚至没有发送一个字节。我的猜测:您的请求格式不正确或不完整。对方正在等待你发送完整的数据。

请注意,读取可能是部分的。您通常需要循环,直到获得所需的所有数据。假设每次读取只返回一个字节。您的代码必须能够处理该问题。您可以尝试 new StreamReader(new NetworkStream(socket)).ReadToEnd()


这个 Microsoft 示例代码太可耻了:

// String to store the response ASCII representation.
String responseData = String.Empty;

// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);

他们确实说这是“第一批”,但代码仍然有问题。

关于vb.net - 在 VB.NET 中通过 TCP/IP 发送数据时程序卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35158976/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com