private void NewConnection(NewClient obj) { // add to list of clients; list.TryAdd(obj.id, obj); string msg = string.Format("[Client {0}] connected", obj.id); WriteToLog(msg); SendTask(msg, obj.id); while (obj.client.Connected) { try { // while the client is connected, constantly read from the buffer asynchronously obj.stream.BeginRead(obj.buffer, 0, obj.buffer.Length, new AsyncCallback(Read), obj); // Block thread until otherwise noted; obj.handle.WaitOne(); } catch (Exception e) { WriteToLog(string.Format("Something went wrong: {0}", e.Message)); } } // Client is no longer connected obj.client.Close(); msg = string.Format("[Client {0}] disconnected", obj.id); WriteToLog(msg); SendTask(msg, obj.id); list.TryRemove(obj.id, out NewClient tmp); }
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(); } } }
private void Read(IAsyncResult result) { NewClient obj = (NewClient)result.AsyncState; int bytes = 0; if (obj.client.Connected) { try { bytes = obj.stream.EndRead(result); } catch (Exception ex) { WriteToLog(string.Format("[/ {0} /]", ex.Message)); } } if (bytes > 0) { obj.data.AppendFormat("{0}", Encoding.UTF8.GetString(obj.buffer, 0, bytes)); try { if (obj.stream.DataAvailable) { obj.stream.BeginRead(obj.buffer, 0, obj.buffer.Length, new AsyncCallback(Read), obj); } else { string msg = string.Format("[Client {0}]: {1}", obj.id, obj.data); WriteToLog(msg); SendTask(msg, obj.id); obj.data.Clear(); obj.handle.Set(); } } catch (Exception ex) { obj.data.Clear(); WriteToLog(string.Format("[/ {0} /]", ex.Message)); obj.handle.Set(); } } else { obj.client.Close(); obj.handle.Set(); } }
private void Write(IAsyncResult ar) { NewClient obj = (NewClient)ar.AsyncState; if (obj.client.Connected) { try { // Completes the async call to `BeginWrite` obj.stream.EndWrite(ar); } catch (Exception e) { Console.WriteLine("Something went wrong: {0}", e.Message); } } }