java - 等待 \n 而不是 EOF C# SslStream
问题描述
我正在使用 SslStream 来接受客户。此代码从套接字读取 2048 个字节并将它们作为字符串返回。当我尝试使用我用 Java 编写的客户端进行连接时,服务器没有回复并卡在这一行:
bytes = sslStream.Read(buffer, 0, buffer.Length);
经过一番谷歌搜索,我发现服务器正在等待 EOF 完成消息。这很烦人,因为我构建的协议需要\n
在消息结束时等待。
有没有办法等待我选择的角色完成消息?我尝试在客户端发送的消息末尾添加 EOF,但没有成功。我通过 发送消息PrintWriter
。我用这个语句(Java)创建了它:
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
socket
是SSLSocket
。我在网上找到的答案有点混乱,并没有解决我的问题。
服务器:
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");
解决方案
经过一番谷歌搜索,我发现为了发送最终信号,我需要使用out.flush()
.
推荐阅读
- android - Android Facebook 登录 - 应用已禁用 - URL 合规性
- android - 如何在android中的外部存储卡上写入
- python - 如何在使用 python 检查是否存在时在 sqlite3 表中插入数据
- wordpress - 如何删除转到 wordpress 的旧本地主机?
- r - 更改数字向量的列名?
- python - 错误:y 无法将字符串转换为浮点 python 随机森林
- reactjs - 如何在 react-bootstrap-table2 (React.js) 中添加特定于行的操作按钮
- android - 如何在 Android 库中获取 Context
- javascript - 在 ReactJS 项目中使用静态 html/css/jquery 登陆页面
- swiftui - SwiftUI,具有统一阴影的多个形状?