chromigo
chromigo

Reputation: 1144

How to receive/send file, data on .net(C#) Sockets and distinguish them

I have async Server and async Client on .net Sockets. Client creates object(for example class UserInfo), serializes him, and writes in byte[]. Also Client has some file(1.png for example). Client need to sent serialized UserInfo and 1.png to the server.

I use for file,

Socket.BeginSendFile Method (String, AsyncCallback, Object)

and for byte[] object

client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);

Server must receive this date together and understand what is file and what is serizalize object(because server has only one method for receive data).

listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
...
AcceptCallback(IAsyncResult ar)
{...
 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
}

and our logic in

ReadCallback(IAsyncResult ar)
    {...}

How to receive this data correctly? In finally i need that server has 1.png and UserInfo object.(and distinguish them). Moreover, because the server is asynchronous, it should not be confused when receiving data from multiple clients simultaneously

i have one idea, but i think this is wrong: Try to use on a client

Socket.BeginSendFile Method (String, Byte[], Byte[], TransmitFileOptions, AsyncCallback, Object)

with byte[] preBuffer, where i will write header, such this "..." and on server i try to find this header, cut it, analyse and do some activity.

Is there a way easier and more correct?

Thanks.

Upvotes: 0

Views: 1341

Answers (1)

sll
sll

Reputation: 62564

Each channel (socket) should have definite and known protocol, in terms of implementation - well known type of objects. So introduce a main class which will encapsulate all data which could be sent via this socket:

public interface IPacketWrapper
{
   IEnumerable<byte> Payload { get; }
   UserInfo UserDetails { get; }
}

So client and server exchange by objects which implements IPacketWrapper so you can put together both binary data and UserInfo, then serialize/deserialize this object on client/server side respectively.

Upvotes: 0

Related Questions