private void ReadSocket(Socket pSocket, SocketStateObject pStateObject) { string message = string.Empty; if (pSocket == null) { return; } // Read data from the socket int bytesRead = 0; try { bytesRead = pSocket.Receive(pStateObject.mBuffer); } catch (Exception e) { Console.WriteLine("Can't read data from remote end "); pSocket.Close(); bytesRead = 0; return; } if (bytesRead > 0) { pStateObject.mSb.Append( Encoding.ASCII.GetString( pStateObject.mBuffer, 0, bytesRead)); if (pSocket.Available > 0) { ReadSocket(pSocket, pStateObject); } message = pStateObject.mSb.ToString(); Console.WriteLine( "Arrived {0} bytes from socket.\n Data: {1}", message.Length, message); // Process with the incoming data here // Data exchange, decoding DataEncoderImpl.Decapsulate(message); } }
private void ReadSocket(Socket pSocket, SocketStateObject pStateObject) { try { int bytesRead = pSocket.Receive(pStateObject.mBuffer); if (bytesRead > 0) { pStateObject.mSb.Append( Encoding.ASCII.GetString( pStateObject.mBuffer, 0, bytesRead)); if (pSocket.Available > 0) { ReadSocket(pSocket, pStateObject); } } if (pStateObject.mSb.Length > 1) { mMessage = pStateObject.mSb.ToString(); // Process with the incoming data here Console.WriteLine( "Arrived {0} bytes from socket.\n Data: {1}", mMessage.Length, mMessage); // Process with the incoming data here // Data exchange, decoding DataEncoderImpl.Decapsulate(mMessage); } } catch (Exception e) { Console.WriteLine("Can't receive data from the server."); } }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("You missed the program parameters!"); printUsage(); } else if (args[0] == "-c") { ClientImpl client = new ClientImpl(); Console.WriteLine("<Running in client mode>"); try { int colonIndex = args[1].IndexOf(':'); if (colonIndex == -1) { throw new ArgumentException("Invalid host:port format"); } string host = args[1].Substring(0, colonIndex); string port = args[1].Substring(colonIndex + 1); while (!client.Connect(host, Int32.Parse(port))) { Console.WriteLine("Trying to connect to {0}:{1}...", host, port); Thread.Sleep(1000); } } catch (Exception e) { Console.WriteLine("Failed to connect to the server: {0}", e.ToString()); } if (client.IsConnected) { Thread clientReceiveTH = new Thread(client.Receive); clientReceiveTH.Start(); DataEncoderImpl.SendSampleData(client.Send); DataEncoderImpl.SendRandomSampleData(client.Send); } } else if (args[0] == "-s") { ServerImpl server = new ServerImpl(); Console.WriteLine("<Running in server mode>"); if (args.Length < 3) { server.Listening("", int.Parse(args[1])); } else { server.Listening(args[1], Int32.Parse(args[2])); } Thread serverReceiveTH = new Thread(server.Receive); serverReceiveTH.Start(); DataEncoderImpl.SendSampleData(server.Send); DataEncoderImpl.SendRandomSampleData(server.Send); } else { printUsage(); } }