Send and Receive Binary Data

Following code will explain how to send and receive binary data.

Following are the name spaces used

using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

Create Serializable Class
Following is the serializable class to be send and receive

public class SEmployee
public int EmployeeID;
public string Name;
public string Address;
public double Salary;

public SEmployee()
EmployeeID = 0;
Name = null;
Address = null;
Salary = 0.0;

Send Binary data
Following is the code to send the binary data.
1. Create two serializable class SEmployee.
2. Create an instances of TcpClient
3. Create an instances of IFormatter
4. Create an instance of NetworkStream
5. Serialize the data and send it

SEmployee MyEmp1 = new SEmployee();
SEmployee MyEmp2 = new SEmployee();

MyEmp1.EmployeeID = 1;
MyEmp1.Name = "My Name";
MyEmp1.Address = "My Address 1";
MyEmp1.Salary = 50000;

MyEmp2.EmployeeID = 2;
MyEmp2.Name = "My Name1";
MyEmp2.Address = "My Address 2";
MyEmp2.Salary = 10000;

TcpClient MyTcpClient = new TcpClient("", 9050);
IFormatter MyIFormatter = new BinaryFormatter();
NetworkStream MyNetworkStream = MyTcpClient.GetStream();

MyIFormatter.Serialize(MyNetworkStream, MyEmp1);
MyIFormatter.Serialize(MyNetworkStream, MyEmp2);

Receive Binary Data
Following is the code to receive the binary data.
1. Create an instance of TcpListener and start listern the port
2. Create an instances of TcpClient
3. Create an instances of IFormatter
4. Create an instance of NetworkStream
5. Receive the data and Deserialize the SEmployee class.

TcpListener MyTcpListener = new TcpListener(9050);
TcpClient MyTcpClient = MyTcpListener.AcceptTcpClient();
NetworkStream MyNetworkStream = MyTcpClient.GetStream();
IFormatter MyIFormatter = new BinaryFormatter();

SEmployee MyEmp1 = (SEmployee)MyIFormatter.Deserialize(MyNetworkStream);

SEmployee MyEmp2 = (SEmployee)MyIFormatter.Deserialize(MyNetworkStream);

MyNetworkStream .Close();



Author: swetha27 Sep 2012 Member Level: Bronze   Points : 1

hi gudevg

iam developing one project by using networking concepts,i diplayed ipaddress in one textbox now by using that ipaddress i have to send file from client to server.
note:i dont knw how to send file from client to server plz send that code to this id

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: