尝试同时侦听多个端口时出现SocketException C#
本文关键字:SocketException | 更新日期: 2023-09-27 18:26:01
我正在编写一个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
)并仍然侦听两个端口?
如果套接字在特定端口上持续失败,则可能有另一个进程在侦听该端口。
在本地系统上运行端口扫描以确认端口空闲。