71 lines
1.9 KiB
C#
71 lines
1.9 KiB
C#
|
using System;
|
||
|
using System.Net;
|
||
|
using System.Net.Sockets;
|
||
|
using System.Threading;
|
||
|
|
||
|
namespace ln.http
|
||
|
{
|
||
|
public class HttpListener : IDisposable
|
||
|
{
|
||
|
public static int DefaultPort = 80;
|
||
|
|
||
|
|
||
|
private IPEndPoint _localEndPoint;
|
||
|
private Socket _socket;
|
||
|
private HTTPServer _httpServer;
|
||
|
|
||
|
public IPEndPoint LocalEndpoint => _localEndPoint;
|
||
|
|
||
|
public HttpListener(HTTPServer httpServer) : this(httpServer, DefaultPort)
|
||
|
{
|
||
|
}
|
||
|
|
||
|
public HttpListener(HTTPServer httpServer, int port)
|
||
|
{
|
||
|
_httpServer = httpServer;
|
||
|
_localEndPoint = new IPEndPoint(IPAddress.IPv6Any, port);
|
||
|
|
||
|
Initialize();
|
||
|
}
|
||
|
|
||
|
private void Initialize()
|
||
|
{
|
||
|
_socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||
|
_socket.ExclusiveAddressUse = false;
|
||
|
_socket.Bind(_localEndPoint);
|
||
|
_localEndPoint = (IPEndPoint)_socket.LocalEndPoint;
|
||
|
_socket.Listen();
|
||
|
|
||
|
ThreadPool.QueueUserWorkItem((state )=> ListenerThread());
|
||
|
}
|
||
|
|
||
|
private void ListenerThread()
|
||
|
{
|
||
|
while (_socket?.IsBound ?? false)
|
||
|
{
|
||
|
try
|
||
|
{
|
||
|
Socket clientSocket = _socket.Accept();
|
||
|
_httpServer.Connection(
|
||
|
new HttpConnection(
|
||
|
_localEndPoint,
|
||
|
(IPEndPoint)clientSocket.RemoteEndPoint,
|
||
|
new NetworkStream(clientSocket)
|
||
|
)
|
||
|
);
|
||
|
}
|
||
|
catch
|
||
|
{
|
||
|
throw;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public void Dispose()
|
||
|
{
|
||
|
_socket?.Close();
|
||
|
_socket?.Dispose();
|
||
|
_socket = null;
|
||
|
}
|
||
|
}
|
||
|
}
|