Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,


I am working on a socket based client/server application. I want to send a object of my defined Class to server. Here is My Defined class

C#
public class ClientData
{
    int clientId;
    string clientName;
    string message;
    public ClientData(int _id, string _name, string _message)
    {
        this.clientId = _id;
        this.clientName = _name;
        tbis.message = _message
    }
}


I am using asyncronous sockets so i am using Socket.BeginSend function. But my problem is that BeginSend only takes array of bytes as data buffer, i dont know how to convert ClientData object to array of bytes and than convert it back to ClientData object on server side.

thanks in advance for you time.
Posted
Updated 5-Jun-13 1:31am
v3
Comments
bbirajdar 5-Jun-13 6:40am    
Use Serelization
StM0n 5-Jun-13 7:31am    
Could be a good answer +5

1 solution

Using serialization is a good way, however it adds a lot of overhead that you probably don't need. I would add two functions, like:

C#
public byte[] ToBytes()
{
  using (MemoryStream ms = new MemoryStream)
  {
    BinaryWriter bw = new BinaryWriter(ms);
    bw.Write(clientId);
    bw.Write(clientName);
    bw.Write(message);
  
    return ms.ToArray()
  }
}

public static ClientData FromBytes(byte[] buffer)
{
  ClientData retVal = new ClientData();

  using (MemoryStream ms = new MemoryStream(buffer))
  {
    BinaryReader br = new BinaryReader(ms);
    retVal.clientId = br.ReadInt32()
    retVal.clientName = br.ReadString();
    retVal.message = br.ReadString();
  }

  return retVal;
}


Just make sure to initialize your strings to string.empty instead of null so that it can read them and write them correctly.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900