I am trying to connect to a sensor using network, the sensor's ip is 192.168.2.44 on port 3000;
try
{
byte[] byteReadStream = null; // holds the data in byte buffer
IPEndPoint ipe = new IPEndPoint(IPAddress.Any,
3000); //listen on all local addresses and 8888 port
TcpListener tcpl = new TcpListener(ipe);
while (true)
{
//infinite loop
tcpl.Start(); // block application until data and connection
TcpClient tcpc = tcpl.AcceptTcpClient();
byteReadStream = new byte[tcpc.Available]; //allocate space
tcpc.GetStream().Read(byteReadStream, 7000, tcpc.Available);
Console.WriteLine(Encoding.Default.GetString(byteReadStream)
+ "\n")
;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
}
i got this error:
Only one usage of each socket address (protocol/network address/port) is normally permitted
I am so new in socket
It looks like you are trying to open the port each time just to block the application until data is available. Do not try reopening the port. instead let the read function do the waiting
Best way to wait for TcpClient data to become available?
The idea is you interact with the stream,not the TcpClient. then try read some bytes in each go. Of course actual read might be less. In my example I am putting the result in a memory stream. The key is you don't try to reconnect at each loop cycle, because you have opened the port in the pervious loop run.
also consider using this Async, unless you are happy for your thread to be blocked on the read method. Also usually you have to think about closing the port gracefully
while this will fix your code inside this method, but you may get the error due to these reasons. I try to help you uncover them
This method getting called multiple times or by multiple threads. Put some Console.Writeline("This should happen once") at the beginning of the method to detect that
The port is already open!. use 'netstat -an' or some port monitoring products to detect that. I suggest closing visual studio and checking that
you have some automated tests that open the port on your machine.