I have a sensor ,i connect to this sensor using network cable.I should send a command to this sensor to get the value .
The sensor ip is :192.168.2.44
my computer ip:192.168.2.111
I used a program called hercules
as you can see here to connect to the sensor :
In the TCP server
tab i define the port to 3000
when i clicked on listen button
the program shows this (as you can see in the picture) client connected
After connecting i can send a command to the sensor to get the value as you can see in the picture:
I found this code but it does't work and i can't send a command by this to get the value ,the main problem is my code can't connect to the port could you give me some help . i am so new in socket programming .
Code:
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();
}
Exception:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.2.44:3000
I should implement something like the hercules
using c#
In your screenshots, PC is a master device (it opens a listening server socket), and the sensor is a slave. While your code assumes, that PC tries to connect to a sensor as a client.
The minimal code snippet is this:
Also note, that if the protocol is textual, then you could build request and parse response using
StreamWriter
/StreamReader
.