public void Stop() { lock (this) { if (!Running) { return; } m_stopping = true; } // Shutdown all services foreach (IServer server in m_servers) { server.Stop(); } Running = false; // Fire the master stopping event ServerStoppedHandler handler = ServerStopped; if (handler != null) { handler(this); } // Set the event to allow 'Start()' to exit m_complete.Set(); }
private void OnServerStopped(IServer server) { ServerStoppedHandler handler = ServerStopped; if (handler != null) { handler(this); } }
public void Stop() { lock (this) { if (!Running) { return; } Running = false; // Clean up all listeners foreach (StreamSocketListener listener in m_listeners) { listener.Dispose(); } m_listeners.Clear(); m_listeners = null; // Fire the stopped events ServerStoppedHandler handler = ServerStopped; if (handler != null) { handler(this); } } }
public void Start() { // Make sure we are not already running lock (this) { if (Running) { throw new InvalidOperationException("Socket server is already running."); } Running = true; } // Set up the listener and bind ThreadPool.QueueUserWorkItem((arg) => { m_listener = new Socket(SocketType.Stream, ProtocolType.IP); m_listener.Bind(new IPEndPoint(IPAddress.Any, Port)); m_listener.Blocking = true; m_listener.ReceiveTimeout = 100; m_listener.Listen(BackLog); // Wait for incoming connections while (true) { lock (this) { if (!Running) { break; } } try { Socket client; try { client = m_listener.Accept(); } catch (TimeoutException) { // Allow recheck of running status continue; } if (m_handler != null) { string hostname = "0.0.0.0"; IPEndPoint endpoint = client.RemoteEndPoint as IPEndPoint; if (endpoint != null) { hostname = endpoint.Address.ToString(); } ThreadPool.QueueUserWorkItem((e) => { try { if (m_handler != null) { client.ReceiveTimeout = 0; m_handler( this, hostname, new NetworkStream(client, FileAccess.Read, false), new NetworkStream(client, FileAccess.Write, false) ); } } catch (Exception) { // Quietly consume the exception } // Finally, we can close the socket client.Shutdown(SocketShutdown.Both); client.Close(); }); } } catch (Exception) { // Quietly consume the exception } } // Fire the stopped events lock (this) { ServerStoppedHandler handler = ServerStopped; if (handler != null) { handler(this); } } }); }