Home > Computers and Internet > How to serialize object and send by Socket using C#

How to serialize object and send by Socket using C#

Solution:

1.       Lets say there is one object named ‘’ClsFileInformation”  

    [Serializable] 

    public class ClsFileInformation

    { 

        private string _fileName = string.Empty;

        private string _fileSize = string.Empty;

        private int _status = 0;

        private byte[] _fileData;

        private long _fileLength = 0;  

        public string FileName

        {

            get { return _fileName; }

            set { _fileName = value; }

        }

        public string FileSize 

        {

            get { return _fileSize; }

            set { _fileSize = value; }

        }

        public byte[] FileData

        {

            get { return _fileData; }

            set { _fileData = value; }

        }

        public long FileLength

        {

            get { return _fileLength; }

            set { _fileLength = value; }

        }

    }  

Notes: Class must used Serializable Attribute

 

2.       Need to send from one location to another location, must Serialize the object ..

 

       public static void SendFile(string fileFullName, string remoteAddress)

        { 

            try

            {

                IPHostEntry hostIPAddress = Dns.GetHostByName(Environment.MachineName);

 

                IPAddress ipAddress = IPAddress.Parse(remoteAddress);

                IPEndPoint ipEnd = new IPEndPoint(ipAddress, (int)Port.PortFileTransfer);

                ClsFileInformation objFileInfo = new ClsFileInformation();

                FileInfo fullfileName = new FileInfo(fileFullName);

                float fileSize1 = Convert.ToSingle(fullfileName.Length) / 1024;

                string fileSize = fileSize1.ToString("#.00");

                objFileInfo.FileSize = fileSize;  

                long fileSizeInMB = (fullfileName.Length / 1024) / 1024;  

                if (fileSizeInMB > 50)

                {

                    MessageBox.Show("File size is more than 50MB,\n please try with less than and equal to 50 MB");

                    return;

                } 

                byte[] fileData = File.ReadAllBytes(fileFullName); 

                objFileInfo.FileName = fullfileName.Name;

                objFileInfo.FileData = fileData;

                objFileInfo.FileLength = fullfileName.Length; 

                MemoryStream fs = new MemoryStream();

                BinaryFormatter formatter = new BinaryFormatter();

                using (Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP))

                {

                    try

                    {

                        clientSock.Blocking = true;

                        clientSock.Connect(ipEnd);

                        formatter.Serialize(fs, objFileInfo);

                        byte[] buffer = fs.ToArray(); 

                        System.Threading.Thread.Sleep(500);

                        clientSock.SendTo(buffer, ipEnd);

                        System.Threading.Thread.Sleep(500); 

                        clientSock.Close();

                    }

                    catch (Exception ex)

                    {

                        Logger.LogError((object)ex, ErrorType.Warning);

                    }

                }

            }

            catch (Exception ex)

            {

                if (ex.Message == "No connection could be made because the target machine actively refused it")

                {

                    Logger.LogError((object)ex, ErrorType.Warning);

                }

                else

                {

                    Logger.LogError((object)ex, ErrorType.Warning);

                }

            }

        } 

3.       At the destination need to Deserialize the object… 

                       sock.Listen(100);

                    Socket clientSock = sock.Accept(); 

                    byte[] clientData = new byte[1024 * 1024 * 50];

                    int receivedBytesLen = clientSock.Receive(clientData); 

                    BinaryFormatter formattor = new BinaryFormatter();

                    MemoryStream ms = new MemoryStream(clientData);

                    ClsFileInformation objFileInfo = (ClsFileInformation)formattor.Deserialize(ms); 

 

Advertisements
  1. 15/03/2013 at 2:01 am

    Thank you very much. This helped me a lot. I find your example easy to follow. Thanks.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: