Client :
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("127.0.0.1", 9011);
Console.WriteLine("connected...");
BinaryFormatter formatter=new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream();
Person person = new Person() { Name = "Mahmood" };
formatter.Serialize(memoryStream,person);
byte[] dataBytes = memoryStream.ToArray();
socket.Send(dataBytes);
Console.WriteLine("sent...");
memoryStream = new MemoryStream();
byte[] buffer = new byte[1024 * 4];
int readBytes = socket.Receive(buffer);
while (readBytes > 0)
{
memoryStream.Write(buffer, 0, readBytes);
if (socket.Available>0)
{
readBytes = socket.Receive(buffer);
}
else
{
break;
}
}
Console.WriteLine("read...");
formatter=new BinaryFormatter();
// set position to 0 or create a new stream
memoryStream.Position = 0;
Greeting response = (Greeting) formatter.Deserialize(memoryStream);
Console.WriteLine(response.Msg);
memoryStream.Close();
socket.Close();
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();
Console.WriteLine("new connection...");
byte[] buffer = new byte[1024];
int readBytes = newSocket.Receive(buffer);
MemoryStream memoryStream = new MemoryStream();
while (readBytes > 0)
{
memoryStream.Write(buffer, 0, readBytes);
if (socket.Available>0)
{
readBytes = newSocket.Receive(buffer);
}
else
{
break;
}
}
Console.WriteLine("data received...");
BinaryFormatter formatter=new BinaryFormatter();
memoryStream.Position = 0;
Person p = (Person) formatter.Deserialize(memoryStream);
memoryStream.Close();
Greeting g = SayHello(p);
formatter=new BinaryFormatter();
memoryStream=new MemoryStream();
formatter.Serialize(memoryStream,g);
newSocket.Send(memoryStream.ToArray());
memoryStream.Close();
newSocket.Close();
Console.WriteLine("data sent...");