public void ServerThread(object obj) { var clientId = 0; lock (_graphics) { clientId = nextClientId++; } try { using (TcpClient client = (TcpClient)obj) { StreamReader reader = new StreamReader(client.GetStream(), Encoding.UTF8); bool lostConnection = false; while (client.Connected && !lostConnection) { if (client.Client.Poll(100 * 1000, SelectMode.SelectRead)) { // poll returned true, we either have some data or the connection was closed by the client String line; do { // the connection should block here if the client is still alive line = reader.ReadLine(); if (line == null) { // Logger.LogMessage(String.Format("client {0} disconnected..", clientId)); lostConnection = true; break; // client disconnected } if (!String.IsNullOrWhiteSpace(line)) { // try and deserialize the buffer. Logger.LogMessage("got message.."); Graphic request = JsonConvert.DeserializeObject <Graphic>(line); ProcessCommand(request, client); SendGraphic(request, clientId); Logger.LogMessage("sent graphic.."); } } while (line != null); } } } } catch (Exception err) { // maybe log stuff here.. Logger.LogMessage(String.Format("Exception: {0}", err)); Interlocked.Increment(ref this.messageErrorCount); return; } finally { lock (_graphics) { // lost connection, remove this connection's graphics foreach (var gid in _graphics.Keys.ToArray()) { InternalGraphic g = _graphics[gid]; if (g.ClientId == clientId) { _graphics.Remove(gid); } } } } }