c# - 关于优化 C# NET 代码块的反馈

标签 c# .net optimization tcp

我刚刚花了好几个小时阅读 TCP 服务器和我想要实现的协议(protocol),最终一切正常。我注意到代码看起来完全是胡说八道(这是正确的用法吗?我不是英国人)并希望得到一些关于优化它的反馈,主要是为了重用和可读性。

数据包格式总是 int, int, int, string, string。

try
{
    BinaryReader reader = new BinaryReader(clientStream);
    int packetsize = reader.ReadInt32();
    int requestid = reader.ReadInt32();
    int serverdata = reader.ReadInt32();
    Console.WriteLine("Packet Size: {0} RequestID: {1} ServerData: {2}", packetsize, requestid, serverdata);

    List<byte> str = new List<byte>();
    byte nextByte = reader.ReadByte();

    while (nextByte != 0)
    {
        str.Add(nextByte);
        nextByte = reader.ReadByte();
    }

    // Password Sent to be Authenticated
    string string1 = Encoding.UTF8.GetString(str.ToArray());

    str.Clear();
    nextByte = reader.ReadByte();

    while (nextByte != 0)
    {
        str.Add(nextByte);
        nextByte = reader.ReadByte();
    }

    // NULL string
    string string2 = Encoding.UTF8.GetString(str.ToArray());

    Console.WriteLine("String1: {0} String2: {1}", string1, string2);

    // Reply to Authentication Request
    MemoryStream stream = new MemoryStream();
    BinaryWriter writer = new BinaryWriter(stream);

    writer.Write((int)(1)); // Packet Size
    writer.Write((int)(requestid)); // Mirror RequestID if Authenticated, -1 if Failed
    byte[] buffer = stream.ToArray();

    clientStream.Write(buffer, 0, buffer.Length);
    clientStream.Flush();
}

我还将处理其他格式相同 (int/int/int/str/str) 但值不同的数据包类型。我或许可以创建一个数据包类,但这有点超出了我如何将其应用于此场景的知识范围。如果有任何不同,这就是我正在实现的协议(protocol)。

http://developer.valvesoftware.com/wiki/Source_RCON_Protocol

最佳答案

想法:

  • 除了一些整数,你并没有真正使用阅读器;否则,您所需要的只是 ReadByte,您可以从 Stream 中执行此操作,并避免一些间接/混淆
  • 手动读取整数以避免字节顺序问题
  • 逐字节读取可能很昂贵;如果可能,尝试通过遍历 Read 而不是 ReadByte 来填充缓冲区(或者更确切地说:读取正确数量的数据)
  • 如果多个消息通过同一个管道,读到 EOF 可能会失败(要么损坏数据,要么永远阻塞);您通常需要终止符序列或长度前缀。我更喜欢后者,因为它让您可以使用 Read 而不是 ReadByte
  • 我假设在您的示例中是 packetSize;使用它是关键:分隔消息,验证您有完整消息,并拒绝超大数据<
  • 考虑async(BeginRead)是否合适——有时合适,有时不合适;请注意,这会使处理变得更加棘手,因为您不能将“使用”与异步一起使用
  • 使用 MemoryStream 时,使用 .GetBuffer() 结合 .Length 的开销比使用 .ToArray() 少

关于c# - 关于优化 C# NET 代码块的反馈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5283547/

相关文章:

MYSQL - 如何为 group by/order by/sum/with where 添加索引

c# - 对象的可空类型

c# - 协程中的 Vector3.Lerp 在 Unity3D 上无法正常工作

.net - 当我的大型 ASP.NET 站点更新时,IIS 必须重新编译其中的很多内容。有没有办法显着减少我的编译时间?

c# - 查询 IEnumerable 中具有相似属性且在特定时间阈值内的对象

java - Java 中的快速按位操作

c# - 如何使用 LINQ to SQL 将单行添加到列表?

c# - 为什么我无法从 JArray 中删除元素?

c# - 如何在托管的资源管理器浏览器控件中获取大缩略图?

testing - 我可以得到一个常规页面来重定向子目录中的页面吗?