Receive Binary Data from the client
This is one of the example of socket programming
The following is the code for receive the binary data from the client
Namespace part
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
Main code part
public class BinaryDataReceiver
{
public static void Main()
{
TcpListener MyTcpListener = new TcpListener(9050);
MyTcpListener.Start();
TcpClient MyTcpclient = MyTcpListener.AcceptTcpClient();
NetworkStream MyNetworkStream = MyTcpclient.GetStream();
IFormatter Myformatter = new BinaryFormatter();
Employee MyEmployee1 = (Employee)formatter.Deserialize(MyNetworkStream);
Console.WriteLine("MyEmployee1.LastName = {0}", MyEmployee1.LastName);
Console.WriteLine("MyEmployee1.FirstName = {0}", MyEmployee1.FirstName);
Console.WriteLine("MyEmployee1.Salary = {0}\n", MyEmployee1.Salary);
Employee MyEmployee2 = (Employee)formatter.Deserialize(MyNetworkStream);
Console.WriteLine("MyEmployee2.LastName = {0}", MyEmployee2.LastName);
Console.WriteLine("MyEmployee2.FirstName = {0}", MyEmployee2.FirstName);
Console.WriteLine("MyEmployee2.Salary = {0}", MyEmployee2.Salary);
MyNetworkStream.Close();
MyTcpListener.Stop();
}
}
Serializable Employee Class
[Serializable]
public class Employee
{
public string LastName;
public string FirstName;
public double Salary;
public SerialEmployee()
{
LastName = null;
FirstName = null;
Salary = 0.0;
}
}
Code Expalantion
1. Create the Serializable class Employee
2. Create the instancess for the class
3. Create the instance MyTcpListener
4. Create the instance of the Iformatter
5. Create the instance of the NetworkStream
6. Receive the data
By
Nathan
