// ============================================================ // Constructor public HttpServer(int port, httpCallback myCallback) { this.port = port; string hostname = Dns.GetHostName(); foreach (IPAddress tmp in Dns.GetHostAddresses(hostname)) { if (tmp.AddressFamily == AddressFamily.InterNetwork) { SERVIP = tmp.ToString(); EXTERNSERVIP = SERVIP; break; } } Console.WriteLine("Hostname: " + hostname + " - IP: " + SERVIP); if (myCallback != null) { doCallBack = myCallback; } }
// ============================================================ // Listener public void listen() { // Create a new server socket, set up all the endpoints, bind the socket and then listen Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipaddress = IPAddress.Parse(SERVIP); IPEndPoint endpoint = new IPEndPoint(ipaddress, port); try { listener.Bind(endpoint); listener.Blocking = true; listener.Listen(-1); } catch (SocketException e) { Console.WriteLine("SocketException: " + e.ErrorCode + " - " + e.Message); return; } catch (Exception e) { Console.WriteLine("Other exception: " + e.Message); return; } Console.WriteLine("Http server listening on port " + port); bool quit; do { quit = true; try { // Because connection is blocking, only accept when one is present // Poll every 10ms for new connection if (listener.Poll(10000, SelectMode.SelectRead)) { // Accept a new connection from the net, blocking till one comes in Socket s = listener.Accept(); // Create a new processor for this request HttpProcessor processor = new HttpProcessor(s, doCallBack); // Dispatch that processor in its own thread Thread thread = new Thread(new ThreadStart(processor.process)); thread.Start(); } quit = false; } catch (SocketException e) { Console.WriteLine("SocketException: " + e.ErrorCode + " - " + e.Message); } catch (ThreadAbortException) { //Server going down System.Threading.Thread.ResetAbort(); //allow cleanup code below loop } catch (Exception e) { Console.WriteLine("Other exception: " + e.Message); } } while (!quit); listener.Close(); doCallBack = null; Console.WriteLine("Http server is shut down"); }