通过NamedPipe发送多行字符串? [英] Sending a multiline string over NamedPipe?

查看:99
本文介绍了通过NamedPipe发送多行字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在NamedPipe上发送包含空行的多行字符串?

How can I send a multiline string with blank lines over a NamedPipe?

如果我发送字符串

string text= @"line 1 
line2

line four
";
StreamWriter sw = new StreamWriter(client);
sw.Write(text);

我只能在服务器端第1行" :

StreamReader sr = new StreamReader(server);
string message = sr.ReadLine();

当我尝试这样的事情

StringBuilder message = new StringBuilder();
string line;
while ((line = sr.ReadLine()) != null)
{
    message.Append(line + Environment.NewLine);
}

它在客户端连接时挂在循环中,仅在客户端断开连接时才释放.

It hangs in the loop while the client is connected and only releases when the client disconnects.

有什么想法可以在不陷入此循环的情况下获取整个字符串吗? 我需要处理该字符串,并以相同的方式将其返回给客户端.

Any ideas how I can get the whole string without hanging in this loop? I need to to process the string and return it on the same way to the client.

重要的是要保留字符串的原始格式,包括空白行和空格.

It's important that I keep the original formatting of the string including blank lines and whitespace.

推荐答案

StreamReader是面向行的阅读器.它将读取第一行(由换行符终止).如果需要其余文本,则必须发出多个阅读行.那就是:

StreamReader is a line-oriented reader. It will read the first line (terminated by a newline). If you want the rest of the text, you have to issue multiple readlines. That is:

StreamReader sr = new StreamReader(server);
string message = sr.ReadLine(); // will get "line1"
string message2 = sr.ReadLine(); // will get "line2"

您不想在网络流上读到结尾",因为这将使阅读器挂起,直到服务器关闭连接为止.那可能会很长的时间,并且可能会使缓冲区溢出.

You don't want to "read to end" on a network stream, because that's going to hang the reader until the server closes the connection. That might be a very long time and could overflow a buffer.

通常,您会看到以下内容:

Typically, you'll see this:

NetworkStream stream = CreateNetworkStream(); // however you're creating the stream
using (StreamReader reader = new StreamReader(stream))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // process line received from stream
    }
}

这将为您提供接收到的每一行,并在服务器关闭流时终止.

That gives you each line as it's received, and will terminate when the server closes the stream.

如果希望读者将整个多行字符串作为单个实体处理,则不能可靠地使用StreamReader进行处理.您可能要在服务器上使用BinaryWriter,在客户端上使用BinaryReader.

If you want the reader to process the entire multi-line string as a single entity, you can't reliably do it with StreamReader. You'll probably want to use a BinaryWriter on the server and a BinaryReader on the client.

这篇关于通过NamedPipe发送多行字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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