【问题标题】:Wait for \n instead of EOF C# SslStream等待 \n 而不是 EOF C# SslStream
【发布时间】:2020-04-15 02:11:26
【问题描述】:

我正在使用 SslStream 来接受客户端。 此代码从套接字读取 2048 个字节并将它们作为字符串返回。当我尝试使用我用 Java 编写的客户端进行连接时,服务器没有回复并卡在这一行:

bytes = sslStream.Read(buffer, 0, buffer.Length);

经过一番谷歌搜索,我发现服务器正在等待 EOF 完成消息。这很烦人,因为我构建的协议需要在消息末尾等待\n

有没有办法等待我选择的角色完成消息? 我尝试在客户端发送的消息末尾添加 EOF,但没有成功。我通过PrintWriter 发送了消息。我用这个语句(Java)创建了它:

out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));

socketSSLSocket。 我在网上找到的答案有点混乱,并没有解决我的问题。

服务器:

static string ReadMessage(SslStream sslStream) 
{
    // Read the  message sent by the client.
    // The client signals the end of the message using the
    // "<EOF>" marker.
    byte[] buffer = new byte[2048];
    StringBuilder messageData = new StringBuilder();
    int bytes = -1;
    do 
    {
        // Read the client's test message.
        bytes = sslStream.Read(buffer, 0, buffer.Length);

        // Use Decoder class to convert from bytes to UTF8
        // in case a character spans two buffers.
        Decoder decoder = Encoding.UTF8.GetDecoder();
        char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
        decoder.GetChars(buffer, 0, bytes, chars, 0);
        messageData.Append(chars);

        // Check for EOF or an empty message.
        if (messageData.ToString().IndexOf("<EOF>") != -1)
        {
            break;
        }
    } while (bytes != 0);

    return messageData.ToString();
}

在消息末尾添加EOF:

out.print(message + (char)-1);

另外,我试过这个:

out.print(message + "\r\n\r");

【问题讨论】:

  • 您可以控制do {} while();,那么,是什么让您在阅读NL 后无法访问break

标签: java c# ssl printwriter sslstream


【解决方案1】:

经过一番谷歌搜索,我发现为了发送最终信号,我需要使用out.flush() 刷新套接字。

【讨论】:

  • 你说的socket是java客户端socket吧?此外,您可能需要在上面的代码中处理一些事情。 1. SslStream.Read 可以返回 0 字节,在这种情况下一定要中断。 2. 我强烈建议使用异步版本的 Read (ReadAsync),尤其是在客户端和服务器交互时。
  • 确实是客户端套接字,我会检查异步功能。谢谢!
猜你喜欢
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
  • 2017-06-28
  • 1970-01-01
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多