Click here to Skip to main content
15,912,400 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

I have just started to work with sockets and must say its pretty confusing.

When i send the data from client to the server, how do i then separate/identify the type of data on the server that has been sent from a client?

For example:
I want to send username/password for a login. How do i then identify what is the username and what is the password in the byte array?

Best regards
Posted

To Identify messages sent you have to do 2 things:

1) make a data packet.
2) create a protocol for sending and receiving.

Look at my article here for more information.
 
Share this answer
 
Comments
Simon Bang Terkildsen 9-Sep-11 19:20pm    
OP wrote
Well this i have done but do i know if i am receiving the username/password for example? Shall i use some kind of separator or what is the most usual way?
You better send serialized objects than plain text with separators. E.g., create:

enum PacketType
{
    LoginData,
    OtherData
}

public interface IPacket
{
    PacketType PacketType { get; }
}


On your client side create and send:

[Serializable]
public class LoginPacket : IPacket
{
    public PacketType PacketType { get { return PacketType.LoginData; } }
    public string Login { get; private set; }
    public string Password { get; private set; }

    public LoginPacket(string login, string password)
    {
        Login = login;
        Password = password;
    }
}


Send to server
new LoginPacket("username", "password")


And on the server side test the received data object for type and get its content, e.g.:

var receivedPacket = data as IPacket;
switch (receivedPacket.PacketType)
{
    case PacketType.LoginData:
        var loginPacket = data as LoginPacket;
        // check loginPacket.Login and .Password
        break;
    default:
        // other stuff
        break;
}


PS1. It is better to send password hash instead of plain password.

PS2. Check out this article by Roy Triesscheijn: http://royalexander.wordpress.com/2009/05/31/sending-objects-via-high-speed-asynchronous-sockets-in-c-serialization-socket-programming/[^].
 
Share this answer
 
v5
Comments
Simon Bang Terkildsen 9-Sep-11 19:20pm    
OP wrote
Thanks alot,

does this also work with tcpclient/tcplistener?
Aoi Karasu 10-Sep-11 5:35am    
Yeah, for TcpClient you can do memory stream (de)serialization like in Roy's blog post.

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