private void Listener(IPAddress localaddr, int port) { TcpListener listener = null; try { listener = new TcpListener(localaddr, port); listener.Start(); Active(true); while (active) { if (listener.Pending()) { try { MyClient obj = new MyClient(); obj.id = id; obj.nick = null; obj.client = listener.AcceptTcpClient(); obj.stream = obj.client.GetStream(); obj.buffer = new byte[obj.client.ReceiveBufferSize]; obj.data = new StringBuilder(); obj.handle = new EventWaitHandle(false, EventResetMode.AutoReset); Thread th = new Thread(() => Connection(obj)) { IsBackground = true }; th.Start(); id++; } catch (Exception ex) { LogWrite(string.Format("[/ {0} /]", ex.Message)); } } else { Thread.Sleep(500); } } Active(false); } catch (Exception ex) { LogWrite(string.Format("[/ {0} /]", ex.Message)); } finally { if (listener != null) { listener.Server.Close(); } } }
private void StartListening(IPAddress iPAddress, int port) { TcpListener listener = null; try { listener = new TcpListener(iPAddress, port); listener.Start(); Activate(true); WriteToLog("Server Started. Waiting for connections...."); while (active) { if (listener.Pending()) { try { // Create client for pending listener NewClient obj = new NewClient(); obj.id = id; obj.client = listener.AcceptTcpClient(); obj.buffer = new byte[obj.client.ReceiveBufferSize]; obj.stream = obj.client.GetStream(); obj.data = new StringBuilder(); obj.handle = new EventWaitHandle(false, EventResetMode.AutoReset); Thread th = new Thread(() => NewConnection(obj)); th.IsBackground = true; th.Start(); id++; } catch (Exception e) { WriteToLog(string.Format("Something went wrong: {0}", e.Message)); } } } } catch (Exception e) { WriteToLog(string.Format("Something went wrong: {0}", e.Message)); } finally { if (listener != null) { listener.Server.Close(); } } }