public void ReadCallback(IAsyncResult result) { String content = String.Empty; // Retrieve the state object and the handler socket // from the asynchronous state object. StateObject state = (StateObject)result.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. int bytesRead = handler.EndReceive(result); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead)); content = state.sb.ToString(); if (content.IndexOf("<NEXT>") > -1) { Debug.Log("NEXT"); state.sb.Remove(0, state.sb.Length); byte[] currentFrame = clientDataService.GetCurrentFrameAsByteArray(); Send(handler, currentFrame); } else if (content.IndexOf("<PLAY>") > -1) { Debug.Log("PLAY"); state.sb.Remove(0, state.sb.Length); content = content.Substring(0, content.IndexOf("<PLAY>")); string[] toSend = content.Split(new string[] { "<EOL>" }, StringSplitOptions.None); Debug.Log(string.Format("drawing {0} lines from socket. \n", toSend.Length)); clientDataService.ClearLines(); foreach (string line in toSend) { if (!string.IsNullOrEmpty(line)) { Debug.Log(string.Format("line: {0}", line)); clientDataService.DrawCompleteLineFromString(line); } } clientDataService.Play(); handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state ); } else if (content.IndexOf("<RESET>") > -1) { Debug.Log("RESET"); state.sb.Remove(0, state.sb.Length); clientDataService.Stop(); clientDataService.Reset(); handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state ); } else if (content.IndexOf("<QUIT>") > -1) { Debug.Log("QUIT"); state.sb.Remove(0, state.sb.Length); // Closing connection handler.Shutdown(SocketShutdown.Both); handler.Close(); StopListening(); } else { // Not all data received. Get more. handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state ); } } }