通过套接字发送和接收多个变量数据的最佳方式

本文关键字:变量 数据 方式 最佳 套接字 | 更新日期: 2023-09-27 18:34:10

我正在开发一个使用套接字发送和接收数据的游戏项目。客户端游戏是 Unity,服务器是 ASP.Net。

众所周知,在套接字上,您只能发送和接收字节。那么,对我来说,发送和接收多个变量(如速度方向等)的最佳方式是什么。

我认为最好的方法是将所有变量连接成一个字符串并将该字符串转换为一个字节,然后发送并取消连接另一侧的字符串。但也许这不是最好的方法,可能还有其他方法,尤其是在 C# 中。这是我的伪代码,我认为可以很好地工作:

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

我认为这种方式不够高效。我能找到其他方法吗?

通过套接字发送和接收多个变量数据的最佳方式

除非你真的需要一个字符串,否则弄乱字符串是没有意义的。

您可以改用BinaryReaderBinaryWriter。通过这种方式,您可以将有效负载大小保持在最小值,并且不必处理字符串编码(当然,除非写入和读取实际字符串)。

// 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();
}

我认为这种方式不够有效。我能找到其他方法吗?[原文如此]

你还不应该担心这一点。听起来您仍处于项目的第一阶段。我建议先让一些东西工作,但尽量确保你让它可插拔。 这样,如果您认为拥有的解决方案太慢或决定使用其他东西而不是套接字,您可以在以后轻松更换它。

谢谢我的朋友,但我找到了更简单的方法,并选择与您分享。您只需将一些变体设置为一个字符串,然后您可以将其拆分以单独阅读它们。 像下面的代码:

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

谢谢。