我正在尝试使用网络连接到传感器,传感器的IP地址是端口3000上的192.168.2.44;
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();
}
我收到此错误:
Only one usage of each socket address (protocol/network address/port) is normally permitted
我的插座太新了
似乎您只是在每次尝试打开端口时才阻塞应用程序,直到有可用数据为止。不要尝试重新打开端口。而是让read函数等待
byte[] reap = new byte[2048];
var memStream = new MemoryStream();
IPEndPoint ipe = new IPEndPoint(IPAddress.Any,
3000); //listen on all local addresses and 8888 port
TcpListener tcpl = new TcpListener(ipe);
tcpl.Start(); // block application until data and connection
TcpClient tcpc = tcpl.AcceptTcpClient();
int bytesread = tcpc.GetStream().Read(resp, 0, resp.Length);
while (bytesread > 0)
{
memStream.Write(resp, 0, bytesread);
bytesread = tcpc.GetStream().Read(resp, 0, resp.Length);
}
这个想法是您与流进行交互,而不是与TcpClient进行交互。然后尝试每次读取一些字节。当然实际读取的内容可能更少。在我的示例中,我将结果放入内存流中。关键是您不要在每个循环周期都尝试重新连接,因为您已在先前的循环运行中打开了端口。
也可以考虑使用此Async,除非您很高兴在read方法中阻塞线程。通常,您还必须考虑优雅地关闭端口
虽然这将在此方法中修复您的代码,但是由于这些原因,您可能会收到错误消息。我会尽力帮助您发现它们
多次或通过多个线程调用此方法。在方法的开头放置一些Console.Writeline(“这应该发生一次”)以检测到
该端口已打开!使用“ netstat -an”或某些端口监视产品来检测到这一点。我建议关闭Visual Studio并检查一下
您有一些自动测试可以打开计算机上的端口。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句