【问题标题】:Only one usage of each socket address (protocol/network address/port) is normally permitted每个套接字地址(协议/网络地址/端口)通常只允许使用一次
【发布时间】:2011-01-15 19:03:02
【问题描述】:

我正在处理一个使用套接字编程的项目,但是当多次使用同一个套接字时,即使在每次使用套接字时关闭listener() 之后:当我运行应用程序时,它会给出错误:

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

我真的很担心。有人可以帮帮我吗?


这是我正在使用的代码,我正在正确关闭所有连接

        TcpClient tcpClient;
        TcpListener tcpListener;
        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
        {
            tcpClient.ReceiveTimeout = 1;
            tcpClient = tcpListener.AcceptTcpClient();
        }
        catch (Exception ex)
        {
            tcpClient.Close();
            tcpListener.Stop();
        }
        NetworkStream networkStream = tcpClient.GetStream();
        byte[] bytes = new byte[networkStream.Length];
        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;

【问题讨论】:

标签: c# asp.net sockets


【解决方案1】:

您确定您选择的是独一无二的端口吗?

您是否尝试过只使用该端口一次?

确保在重新打开套接字之前真正处理掉连接对象等。没有更多的实现细节很难知道。

【讨论】:

    猜你喜欢
    • 2019-05-03
    • 2017-06-09
    • 2010-11-23
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    相关资源
    最近更新 更多