virtouso
virtouso

Reputation: 569

best way to send and receive multiple variable data through socket

I am working on a game project that uses sockets for sending and receiving data. Client games are Unity, the server is ASP.Net.

As we all know on sockets you just can send and receive bytes. So, what is the best way for me to send and receive multiple variables like speed direction and so on.

I think the best way is to concat all variables to a string and convert that string to a byte and after that send and un concat the string at the other side. But maybe its not the best way and there might be other ways especially in C#. Here is my pseudocode that I think can work well:

 int position,rotation;
 string data=concat(data,position,rotation);
 byte[] byteBuffer = Encoding.ASCII.GetBytes(data);
 socket.send(bytebuffer);

I think this way can not be efficient enough. Can I find some other way?

Upvotes: 1

Views: 2618

Answers (2)

virtouso
virtouso

Reputation: 569

thank you my friends but i found much simpler way and chose to share that with you.you just can set some varibales into an string and after that you can split that to read them seperatly. like code bellow:

string s = "first,second,x";
 string[] s2=s.Split(',');
 Console.WriteLine(s2[0]);
 Console.ReadLine();

thank you.

Upvotes: 1

TyCobb
TyCobb

Reputation: 9089

No sense in messing with strings unless you actually need a string.

You can use BinaryReader and BinaryWriter instead. This way you keep your payload size to a minimum and you don't have to deal with string encodings (unless writing and reading an actual string of course).

// Client
using(var ms = new MemoryStream())
{
   using (var writer = new BinaryWriter(ms))
   {
       //writes 8 bytes
       writer.Write(myDouble);

       //writes 4 bytes
       writer.Write(myInteger);

       //writes 4 bytes
       writer.Write(myOtherInteger);
   }    
   //The memory stream will now have all the bytes (16) you need to send to the server
}

// Server
using (var reader = new BinaryReader(yourStreamThatHasTheBytes))
{
    //Make sure you read in the same order it was written....

    //reads 8 bytes
    var myDouble = reader.ReadDouble();

    //reads 4 bytes
    var myInteger = reader.ReadInt32();

    //reads 4 bytes
    var myOtherInteger = reader.ReadInt32();
}

i think this way can not be efficient enough. can i find some other way? [sic]

You shouldn't worry about that yet. It sounds like you are still at the first stages of the project. I recommend just getting something working first, but trying to make sure that you make it pluggable. That way you can easily swap it out later on if you think the solution you have is too slow or decide to use something else instead of a socket.

Upvotes: 2

Related Questions