ln.json/network/JSONTcpServer.cs

75 lines
1.3 KiB
C#

using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace sharp.json.network
{
public delegate void JSONClientConnected(JSONTcpClient jsonClient);
public class JSONTcpServer
{
public JSONClientConnected ClientConnected { get; set; }
TcpListener listener;
Thread serverThread;
bool shouldExit;
public JSONTcpServer(int port)
{
this.listener = new TcpListener(IPAddress.Loopback, port);
}
public void Start()
{
lock (this){
if (serverThread == null){
serverThread = new Thread(Serve);
serverThread.Start();
}
}
}
public void Stop()
{
lock (this){
shouldExit = true;
this.listener.Stop();
Monitor.Wait(this);
this.serverThread = null;
}
}
public void Serve()
{
this.listener.Start();
while (true){
lock (this){
if (shouldExit){
shouldExit = false;
Monitor.Pulse(this);
break;
}
}
try {
TcpClient client = this.listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem((state) => fireClientConnected(client));
} catch (SocketException se){
}
}
}
private void fireClientConnected(TcpClient client){
if (ClientConnected != null){
JSONTcpClient jsonCLient = new JSONTcpClient(client);
ClientConnected.Invoke(jsonCLient);
}
}
}
}