private void ProcessInternally(AbstractServerHandler serverHandler) { TcpListener listener = null; try { _isConnected = true; var addresses = Dns.GetHostAddresses(_configuration.Host); listener = new TcpListener(addresses[0], _configuration.Port); listener.Start(); while (_isConnected) { var acceptedTcpClient = listener.AcceptTcpClient(); var thread = new Thread(obj => { AbstractClientHandler handler = null; TcpClient client = null; try { handler = serverHandler.CreateClientHandler(); handler.PreStart(); client = (TcpClient)obj; var stream = client.GetStream(); var reader = new StreamReader(stream); var writer = new StreamWriter(stream); while (_isConnected) { IMessage msgToSend; while (handler.TryGetMessage(out msgToSend)) { writer.WriteLine(Serialize(msgToSend)); writer.Flush(); } writer.WriteLine(Serialize(SystemGetMessage.Instance)); writer.Flush(); var msg = Deserialize(reader.ReadLine()); handler.Handle(msg); } } catch (Exception) { //Ignored. Just close close connection. } finally { client?.Close(); handler?.PostStop(); } }); thread.Start(acceptedTcpClient); } } finally { listener?.Stop(); } }
private void ProcessInternally(AbstractClientHandler handler) { TcpClient tcpClient = null; try { _isConnected = true; handler.PreStart(); tcpClient = new TcpClient(_configuration.Host, _configuration.Port); var stream = tcpClient.GetStream(); var reader = new StreamReader(stream); var writer = new StreamWriter(stream); while (_isConnected) { var msg = Deserialize(reader.ReadLine()); if (msg is SystemGetMessage) { IMessage messageToSend; writer.WriteLine(handler.TryGetMessage(out messageToSend) ? Serialize(messageToSend) : Serialize(SystemNope.Instance)); writer.Flush(); } else { handler.Handle(msg); } } } catch (Exception) { //Ignored. Just close connection } finally { tcpClient?.Close(); handler.PostStop(); } }