Skip to content

Instantly share code, notes, and snippets.

@SergeyTeplyakov
Created December 23, 2013 21:24
Show Gist options
  • Save SergeyTeplyakov/8104932 to your computer and use it in GitHub Desktop.
Save SergeyTeplyakov/8104932 to your computer and use it in GitHub Desktop.
SocketServer from PPP book by Robet C. Martin
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public interface SocketService
{
void Serve(Socket s);
}
public class SocketServer
{
private TcpListener serverSocket = null;
private Thread serverThread = null;
private bool running = false;
private SocketService itsService = null;
private ArrayList threads = new ArrayList();
public SocketServer(int port, SocketService service)
{
itsService = service;
IPAddress addr = IPAddress.Parse("127.0.0.1");
serverSocket = new TcpListener(addr, port);
serverThread = new Thread(new ThreadStart(Server));
serverThread.Start();
}
public void Close()
{
running = false;
serverThread.Interrupt();
serverSocket.Stop();
serverThread.Join();
WaitForServiceThreads();
}
private void Server()
{
serverSocket.Start();
running = true;
while (running)
{
Socket s = serverSocket.AcceptSocket();
StartServiceThread(s);
}
}
private void StartServiceThread(Socket s)
{
Thread serviceThread =
new Thread(new ServiceRunner(s, this).ThreadStart());
lock (threads)
{
threads.Add(serviceThread);
}
serviceThread.Start();
}
private void WaitForServiceThreads()
{
while (threads.Count > 0)
{
Thread t;
lock (threads)
{
t = (Thread)threads[0];
}
t.Join();
}
}
internal class ServiceRunner
{
private Socket itsSocket;
private SocketServer itsServer;
public ServiceRunner(Socket s, SocketServer server)
{
itsSocket = s;
itsServer = server;
}
public void Run()
{
itsServer.itsService.Serve(itsSocket);
lock (itsServer.threads)
{
itsServer.threads.Remove(Thread.CurrentThread);
}
itsSocket.Close();
}
public ThreadStart ThreadStart()
{
return new ThreadStart(Run);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment