我有一个传感器,我使用网线连接到此传感器。我应该向此传感器发送命令以获取值。
The sensor ip is :192.168.2.44
my computer ip:192.168.2.111
我使用了一个名为hercules
的程序,你可以看到这里连接到传感器:
在TCP server
标签中我定义了3000
的端口,当我点击listen button
时,程序会显示此信息(如图所示)client connected
连接后,我可以向传感器发送命令以获取值,如图所示:
我找到了这段代码,但它确实无法正常工作,我无法通过此方式发送命令来获取值,主要问题是我的代码无法连接到端口。我一些帮助。我是套接字编程的新手。
代码:
try
{
string hostname = "192.168.2.44";
int portno = 3000;
IPAddress ipa = Dns.GetHostAddresses(hostname)[0];
try
{
System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
sock.Connect(ipa, portno);
if (sock.Connected == true) // Port is in use and connection is successful
Console.WriteLine("Port is Closed");
sock.Close();
}
catch (System.Net.Sockets.SocketException ex)
{
if (ex.ErrorCode == 10061) // Port is unused and could not establish connection
Console.WriteLine("Port is open");
else
Console.WriteLine(ex.ErrorCode);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
}
例外:
连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应192.168.2.44:3000
我应该使用c#
实现类似hercules
的内容
答案 0 :(得分:1)
在屏幕截图中,PC是主设备(它打开监听服务器套接字),传感器是从设备。当您的代码假设时,该PC尝试作为客户端连接到传感器。
最小代码段是:
var listener = new TcpListener(IPAddress.Any, 3000);
listener.Start();
using (var client = listener.AcceptTcpClient())
using (var stream = client.GetStream())
{
// build a request to send to sensor
var request = new byte[] { /*...*/ };
stream.Write(request, 0, request.Length);
// read a response from sensor;
// note, that respose colud be broken into several parts;
// you should determine, when reading is complete, according to the protocol for the sensor
while (!/* response is complete */)
{
// stream.Read calls here
}
}
另请注意,如果协议是文本的,那么您可以使用StreamWriter
/ StreamReader
构建请求和解析响应。