C#网络流getString方法 [英] C# Network Stream getString method

查看:218
本文介绍了C#网络流getString方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个库,以简化以后的项目中的网络编程。我希望它既强大又高效,因为将来我的几乎所有项目都将使用它。 (顺便说一句,服务器和客户端都将使用我的库,所以我不假设我的问题是协议)我正在编写一个函数,用于从网络流中接收字符串,其中我使用31个字节的缓冲区,其中一个用于哨兵。前哨值将指示哪个字节是EOF。这是我的代码供您使用或检查...

I'm writing a library to simplify my network programming in future projects. I'm wanting it to be robust and efficient because this will be in nearly all of my projects in the future. (BTW both the server and the client will be using my library so I'm not assuming a protocol in my question) I'm writing a function for receiving strings from a network stream where I use 31 bytes of buffer and one for sentinel. The sentinel value will indicate which byte if any is the EOF. Here's my code for your use or scrutiny...

public string getString()
    {
        string returnme = "";
        while (true)
        {
            int[] buff = new int[32];
            for (int i = 0; i < 32; i++)
            {
                buff[i] = ns.ReadByte();
            }
            if (buff[31] > 31) { /*throw some error*/}
            for (int i = 0; i < buff[31]; i++)
            {
                returnme += (char)buff[i];
            }
            if (buff[31] != 31)
            {
                break;
            }
        }
        return returnme;
    }

编辑:这是完成任务的最佳方法(高效,实用等)我正在做。

Is this the best (efficient, practical, etc) to accomplish what I'm doing.

推荐答案


这是完成我正在做的最好的事情(高效,实用等)

Is this the best (efficient, practical, etc) to accomplish what I'm doing.

否。首先,您将自己限制为0-255码点范围内的字符,而还不够;其次:字符串序列化已解决。只需使用编码,通常为UTF-8。作为网络流的一部分,这可能意味着编码长度,对数据进行编码和读取长度,缓冲那么多数据,对数据进行解码。另请注意:如果 ReadByte()返回负值,您将无法正确处理EOF方案。

No. Firstly, you are limiting yourself to characters in the 0-255 code-point range, and that isn't enough, and secondly: serializing strings is a solved problem. Just use an Encoding, typically UTF-8. As part of a network stream, this probably means "encoode the length, encode the data" and "read the length, buffer that much data, decode the data". As another note: you aren't correctly handling the EOF scenario if ReadByte() returns a negative value.

作为一个小的推论,请注意在循环中附加到 string 从来都不是一个好主意。如果您这样做 ,请使用 StringBuilder 。但是,不要那样做。我的代码更像是(嘿,瓦迪亚,这是我从protobuf-net实际读取字符串的代码,简化了一点):

As a small corollary, note that appending to a string in a loop is never a good idea; if you did do it that way, use a StringBuilder. But don't do it that way. My code would be something more like (hey, whadya know, here's my actual string-reading code from protobuf-net, simplified a bit):

// read the length         
int bytes = (int)ReadUInt32Variant(false);
if (bytes == 0) return "";

// buffer that much data
if (available < bytes) Ensure(bytes, true);

// read the string
string s = encoding.GetString(ioBuffer, ioIndex, bytes);

// update the internal buffer data
available -= bytes;
position += bytes;
ioIndex += bytes;
return s;

如果要发送结构化消息,请认真考虑使用专门用于此方面的预卷序列化API。例如,您可以执行以下操作:

As a final note, I would say: if you are sending structured messages, give some serious consideration to using a pre-rolled serialization API that specialises in this stuff. For example, you could then just do something like:

var msg = new MyMessage { Name = "abc", Value = 123, IsMagic = true };
Serializer.SerializeWithLengthPrefix(networkStream, msg);

,另一端:

var msg = Serializer.DeserializeWithLengthPrefix<MyMessage>(networkStream);
Console.WriteLine(msg.Name); // etc

工作完成。

这篇关于C#网络流getString方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆