尝试同时侦听多个端口时出现SocketException C#

时间:2015-12-07 11:51:54

标签: c# sockets http ssl networking

我正在编写HTTP服务器,我想同时收听两个端口。
我创建了两个套接字和两个endPoint,我将它们传递给线程。
当代码位于socket.Bind(endPoint);时,我收到以下异常:

System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted

代码:

public class HTTPServer
{
    private readonly IPEndPoint m_LocalEndPoint=new IPEndPoint(IPAddress.Any, 8082);;
    private readonly IPEndPoint m_SecuredLocalEndPoint=new IPEndPoint(IPAddress.Any, 8083);
    private readonly Socket m_SocketListener=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);;
    private readonly Socket m_SecureSocketListener=new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);; 

    public void Start()
        {

            Thread t = ThreadFactory.Create(() => AsyncStart(m_LocalEndPoint,m_SocketListener));
            t.Name = string.Format("HTTPServer({0})", this);
            t.Start();
            Thread sucureThread = ThreadFactory.Create(() => AsyncStart(m_SecuredLocalEndPoint,m_SecureSocketListener));
            sucureThread.Name = string.Format("HTTPSServer({0})", m_SecuredLocalEndPoint);
            sucureThread.Start();
        }


    private void AsyncStart(IPEndPoint endPoint, Socket socket)
        {
            try
            {
                socket.Bind(endPoint);
                socket.Listen(MAX_NUMBER_OF_PENDING_CONNECTIONS);
                Socket clientSocket = socket.Accept();
            }
            catch (Exception ex)
            {
            }          
        }
}

我不知道它是否与该问题相关,但我想听两个端口的原因是我希望能够在同一服务器上处理HTTP和HTTPS请求。
因此,如果客户端将数据包发送到端口8082,我将处理它 HTTP请求,如果他发送到8083,我会将其作为HTTPS处理。
我错过了什么或如何解决这个问题(避免SocketException)并仍然听两个端口?

1 个答案:

答案 0 :(得分:2)

如果套接字在特定端口上一致失败,则可能是有另一个进程正在侦听该端口。

在本地系统上运行端口扫描以确认端口是空闲的。