Client :
Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); socket.Connect("127.0.0.1",9011); Console.WriteLine("connected..."); Person person=new Person(){Name = "Mahmood"}; string jsonData = JsonConvert.SerializeObject(person); byte[] dataBytes = Encoding.Default.GetBytes(jsonData); socket.Send(dataBytes); Console.WriteLine("sent..."); byte[] buffer=new byte[1024*4]; int readBytes = socket.Receive(buffer); MemoryStream memoryStream = new MemoryStream(); while (readBytes>0) { memoryStream.Write(buffer, 0, readBytes); if (socket.Available > 0) { readBytes = socket.Receive(buffer); } else { break; } } Console.WriteLine("read..."); byte[] totalBytes = memoryStream.ToArray(); memoryStream.Close(); string readData = Encoding.Default.GetString(totalBytes); Greeting response = JsonConvert.DeserializeObject<Greeting>(readData); Console.WriteLine(response.Msg); Console.ReadKey();
Server :
Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); EndPoint endPoint=new IPEndPoint(IPAddress.Any, 9011); socket.Bind(endPoint); socket.Listen(5); while (true) { Console.WriteLine("waiting for new connection..."); Socket newSocket = socket.Accept(); MemoryStream memoryStream = new MemoryStream(); Console.WriteLine("new connection..."); byte[] buffer=new byte[1024]; int readBytes = newSocket.Receive(buffer); while (readBytes>0) { memoryStream.Write(buffer,0,readBytes); if (socket.Available > 0) { readBytes = newSocket.Receive(buffer); } else { break; } } Console.WriteLine("data received..."); byte[] totalBytes = memoryStream.ToArray(); memoryStream.Close(); string readData = Encoding.Default.GetString(totalBytes); Person p= JsonConvert.DeserializeObject<Person>(readData); Greeting g = SayHello(p); string dataToSend = JsonConvert.SerializeObject(g); byte[] dataToSendBytes = Encoding.Default.GetBytes(dataToSend); newSocket.Send(dataToSendBytes); newSocket.Close(); Console.WriteLine("data sent..."); }