我正在使用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()
刷新套接字。