我正在连接到 Asp.Net 中的 TCP/IP 端口,基本上我已经在我正在读取的这个端口上连接了一个设备,它工作正常但是第二次当 tcp 监听器尝试启动时它会生成上面的内容错误。 任何人都可以指导我如何摆脱这个错误这是我用来连接到 TCP/IP 端口的代码:
try
{
byte[] ipaddress = new byte[4];
string ip = ConfigurationManager.AppSettings["IP"].ToString();
string[] ips = ip.Split('.');
ipaddress[0] = (byte)Convert.ToInt32(ips[0]);
ipaddress[1] = (byte)Convert.ToInt32(ips[1]);
ipaddress[2] = (byte)Convert.ToInt32(ips[2]);
ipaddress[3] = (byte)Convert.ToInt32(ips[3]);
int portNumber = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);
tcpListener = new TcpListener(new IPAddress(ipaddress), portNumber);
tcpListener.Start();
tcpClient = new TcpClient();
tcpClient.NoDelay = true;
try
{
System.Threading.Thread.Sleep(60000);
tcpClient.ReceiveTimeout = 10;
tcpClient = tcpListener.AcceptTcpClient();
}
catch (Exception ex)
{
tcpClient.Close();
tcpListener.Stop();
}
NetworkStream networkStream = tcpClient.GetStream();
byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
try
{
networkStream.ReadTimeout = 2000;
networkStream.Read(bytes, 0, bytes.Length);
}
catch (Exception ex)
{
tcpClient.Close();
tcpListener.Stop();
}
string returndata = Encoding.Default.GetString(bytes);
tcpClient.Close();
tcpListener.Stop();
return returndata.Substring(returndata.IndexOf("0000000036"), 170);
}
catch (Exception ex)
{
if (tcpClient != null)
tcpClient.Close();
tcpListener.Stop();
LogError("Global.cs", "ReceiveData", ex);
ReceiveData();
}
当它出现在这一行时 tcpListener.Start();第二次然后它生成该错误 “通常只允许每个套接字地址(协议(protocol)/网络地址/端口)使用一次”
最佳答案
如果这是在循环中或其他情况下,请注意如果您的代码没有触发任何异常,则连接不会关闭。它仅在出现异常时关闭,该异常将被结尾的 catch
block
关于c# - 每个套接字地址(协议(protocol)/网络地址/端口)通常只允许使用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2240990/