/// <summary> /// Called to added new port to be listened by HttpServer /// </summary> /// <param name="p">Detail information of the port</param> public void AddPort(TcpPortInfo p) { lock (staLock) { if (running) { ManageListeningContext context = new ManageListeningContext(); context.PortInfo = p; if (p.IsSSL && p.ServerCertificate == null) { throw new Exception("Port " + p.Port.ToString() + " is set to using SSL but server certificate is NULL"); } // start create the listening thread context.Listener = new TcpListener(IPAddress.Any, p.Port); // NEVER catch exception here, we need directly know what happens when we require a Port context.Listener.Start(); context.ListeningThread = new Thread(new ParameterizedThreadStart(ListenLoop)); context.ListeningThread.Start(context); lock (m_listeners) { m_listeners.Add(p.Port, context); } } else { throw new Exception("Not running"); } } }
/// <summary> /// Tcp Listen thread /// </summary> private void ListenLoop(object o) { ManageListeningContext context = o as ManageListeningContext; Trace.WriteLine("Server listener started"); while (this.running) { TcpClient client = null; try { client = context.Listener.AcceptTcpClient(); } catch { Trace.TraceError("client side may disconnected"); return; } Trace.WriteLine(string.Format("Client {0} connected", (client.Client.RemoteEndPoint as IPEndPoint).ToString())); lock (context) { ManagedStream ms = new ManagedStream(); ms.LocalTcpClient = client; ms.PortInfo = context.PortInfo; ms.RemoteEndpoint = client.Client.RemoteEndPoint as IPEndPoint; Thread task = new Thread(new ParameterizedThreadStart(ReceiveLoop)); task.Start(ms); lock (clientStreams) { clientStreams.Add(ms); } context.ReceiveThreads.Add(task); } } }