110 lines
2.9 KiB
C#
110 lines
2.9 KiB
C#
using System;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Threading;
|
|
|
|
namespace VAR.HttpServer
|
|
{
|
|
public class HttpServer
|
|
{
|
|
protected int _port = 8000;
|
|
public int Port
|
|
{
|
|
get { return _port; }
|
|
set
|
|
{
|
|
if (_isActive) { throw new Exception("HttpServer: Can't set port while active"); }
|
|
_port = value;
|
|
}
|
|
}
|
|
|
|
private TcpListener _listener = null;
|
|
|
|
private Thread _thread = null;
|
|
|
|
private bool _isActive = false;
|
|
public bool IsActive { get { return _isActive; } }
|
|
|
|
private IHttpHandler _handler = null;
|
|
public IHttpHandler Handler
|
|
{
|
|
get { return _handler; }
|
|
set { _handler = value; }
|
|
}
|
|
|
|
private Action<string> _logDebugMessage = null;
|
|
public Action<string> LogDegugMessage { set { _logDebugMessage = value; } }
|
|
|
|
private Action<Exception> _logException = null;
|
|
public Action<Exception> LogException { set { _logException = value; } }
|
|
|
|
private void ListenConnections()
|
|
{
|
|
try
|
|
{
|
|
while (_isActive)
|
|
{
|
|
TcpClient client = _listener.AcceptTcpClient();
|
|
HttpProcessor responseProcessor = new HttpProcessor(client, _handler, _logDebugMessage, _logException);
|
|
Thread responseThread = new Thread(new ThreadStart(responseProcessor.Process));
|
|
responseThread.Start();
|
|
}
|
|
_listener = null;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
_isActive = false;
|
|
}
|
|
}
|
|
|
|
public bool Start()
|
|
{
|
|
try
|
|
{
|
|
if (_isActive || _thread != null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_listener = new TcpListener(IPAddress.Any, _port)
|
|
{
|
|
ExclusiveAddressUse = false
|
|
};
|
|
_listener.Start();
|
|
_isActive = true;
|
|
_thread = new Thread(new ThreadStart(ListenConnections));
|
|
_thread.Start();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logException?.Invoke(ex);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public bool Stop()
|
|
{
|
|
try
|
|
{
|
|
if (_isActive == false || _thread == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_isActive = false;
|
|
if (_listener != null)
|
|
{
|
|
_listener.Stop();
|
|
}
|
|
_thread = null;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logException?.Invoke(ex);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
} |