private void HandleClientCommunication(object client) { try { if (!(client is TcpUser user)) { throw new InstanceNotFoundException("TcpUser was not found"); } var clientStream = user.ClientStream; var message = new byte[32768]; while (true) { int bytesRead; try { //// blocks until a client sends a message bytesRead = clientStream.Read(message, 0, 32768); } catch (IOException ex) { ex.Handle(ExceptionHandlingOptions.RecordOnly, Log); break; } catch (ObjectDisposedException ex) { ex.Handle(ExceptionHandlingOptions.RecordOnly, Log); break; } if (bytesRead == 0) { //// the client has disconnected from the server Log.InfoFormat("Client[{0}, {1}] disconnected.", user.Id, user.IpAddress); break; } //// message has successfully been received var encoder = new ASCIIEncoding(); OnNetworkMessageReceived?.Invoke(user, new NetworkEventArgs { Message = encoder.GetString(message, 0, bytesRead) }); } OnTcpUserStatusChanged?.Invoke(user, new NetworkEventArgs { SocketStatus = TcpSocketStatus.Disconnected }); //// lost the user Repository.Delete(user.Id); Log.InfoFormat("Connection Lost from {0}", user.IpAddress); } catch (InstanceNotFoundException ex) { ex.Handle(ExceptionHandlingOptions.RecordAndThrow, Log); } }
private void ListenForClients() { try { _tcpListener.Start(); Log.InfoFormat("TcpServer Listening on {0}", _tcpListener.LocalEndpoint); Status = TcpServerStatus.Listening; OnTcpServerStatusChanged?.Invoke(this, new NetworkEventArgs { ServerStatus = Status }); while (true) { //// blocks until a client has connected to the server if (_listenerThread.ThreadState != ThreadState.Running) { Log.InfoFormat("Listener Thread state {0}", _listenerThread.ThreadState); break; } var user = new TcpUser(Log, _tcpListener.AcceptTcpClient(), Formatters); user.OnConnect(); Repository.Add(user.Id, user); OnTcpUserStatusChanged?.Invoke(user, new NetworkEventArgs { SocketStatus = TcpSocketStatus.Connected }); //// create a thread to handle communication with connected client var clientThread = new Thread(HandleClientCommunication); clientThread.Start(user); } } catch (SocketException ex) { ex.Handle(ExceptionHandlingOptions.RecordAndThrow, Log); } }