c# - 每个套接字地址(协议(protocol)/网络地址/端口)通常只允许使用一次

标签 c# asp.net sockets tcp

我正在连接到 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/

相关文章:

c# - 如何使用资源构建独立的exe?

javascript - 使用 jQuery 从 Json 填充选择/选项时,ASP.NET MVC 清空选择

c# - 使用 asp-ajax 按顺序加载项目并提高 Web 应用程序速度

c# - GroupPrincipal.Members.Add(userPrincipal) 抛出错误

linux - socat 监听分配给特定网络接口(interface)的所有 IP

c# - 什么是消息泵?

c# - Asp.net MVC 模型绑定(bind)派生类

asp.net - 使用 Secret Manager 工具的 ASP .NET Core 1.1 web api

node.js - NodeJS、OpenCV 和使用 Net Socket 的流图像

java - Play2 长期套接字连接和多线程