我有一个程序将数据发送到服务器,并在尝试发送数据时冻结。
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连接,并认为微软可能是一个很好的资源来学习。我已经验证服务器IP和端口是有效的,并接受我的连接。
答案 0 :(得分:0)
认为微软可能是一个很好的资源来学习
哈哈哈...... :( 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);
他们确实说这是“第一批”,但仍然使代码破碎。