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

标签 c# sockets

我正在开发一个使用套接字发送和接收数据的游戏项目。客户端游戏是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();
}

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

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

关于c# - 通过套接字发送和接收多个变量数据的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457142/

相关文章:

c# - 在 C# 中从智能表中检索行数据

C# 扩展

C++ IP 地址人类可读形式

Linux套接字不关闭

java - ExecutorService 未正确调用 Interrupt()

c# - 使用 Selenium 使用 WindowHandles 跟踪和迭代选项卡和窗口的最佳方法

c# - 在 WPF 中为不透明蒙版下方的内容设置动画时,如何保持不透明蒙版静止不动?

c# - 访问多个文件

c - C语言多客户端服务器通信程序如何同时使用writefds和readfds?

android - NDK 上的套接字(AF_INET、SOCK_DGRAM、IPPROTO_ICMP)