【发布时间】:2018-08-26 22:58:46
【问题描述】:
我正在尝试接收来自设备的消息。本设备为鉴权终端,用户设置凭据后立即发送消息。
另外,设备说明书上说信息会以ILV格式发送,代表I代表标识,L代表长度,V代表价值。
正常的消息是:
I -> 0x00 (byte 0 indicating success)
L -> 0x04 0x00 (two bytes for length, being 4 the length in this case)
V -> 0x35 0x32 0x38 0x36 (the message itself)
消息是在 TCP 协议中发送的,所以我使用 TcpListener 类创建了一个套接字,遵循 Microsoft 的这个示例:
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=vs.110).aspx
new Thread(() =>
{
TcpListener server = null;
try
{
Int32 port = 11020;
IPAddress localAddr = IPAddress.Parse("192.168.2.2");
server = new TcpListener(localAddr, port);
server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
server.Start();
byte[] bytes = new byte[256];
String data = null;
while (true)
{
TcpClient client = server.AcceptTcpClient();
data = null;
NetworkStream stream = client.GetStream();
int i = 0;
while((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// this code is never reached as the stream.Read above runs for a while and receive nothing
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
}
client.Close();
}
}
catch (SocketException ex)
{
// Actions for exceptions.
}
finally
{
server.Stop();
}
}).Start();
如果 stream.Read 被删除,那么代码就会流动(虽然我什么也没有得到),但是如果我放置任何 stream.Read 语句,执行会持续一段时间,就像它在等待某个响应一样,然后它结束没有响应,读取的所有字节都为零。
我正在计算机上运行 Wireshark,并且正在发送数据。
有人知道我做错了什么吗?
【问题讨论】: