1
我已阅读similar question,但我的问题没有解决。Java WebSocket服务器OutputStream不冲水
为了学习,我试图构建自己的Java WebSocket服务器。服务器设置良好,它接受传入连接并从客户端获取握手数据。然后,我的服务器计算握手返回数据并尝试写入并刷新它。尽管如此,在Web检查器中,客户端没有显示任何响应头,并且永远不会触发-JavaScript事件。
String EOL = System.getProperty("line.separator"); // actually a class-defined constant
BufferedReader inputStream = currentClient.getInputStream();
OutputStream outputStream = currentClient.getOutputStream();
String inputLine;
String handshake = "";
try {
if(!inputStream.ready()){ continue; }
System.out.println("Receiving:\n");
while ((inputLine = inputStream.readLine()).length() > 0) {
if(inputLine.startsWith("Sec-WebSocket-Key: ")){
String inputKey = inputLine.replace("Sec-WebSocket-Key: ", "");
String outputKey = WebSocket.getWebSocketKey(inputKey);
handshake += "HTTP/1.1 101 Switching Protocols"+EOL;
handshake += "Upgrade: websocket"+EOL;
handshake += "Connection: Upgrade"+EOL;
handshake += "Sec-WebSocket-Accept: "+outputKey;
}
System.out.println(inputLine);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("\n\nSending:\n");
System.out.println(handshake);
try {
outputStream.write(handshake.getBytes(Charset.forName("UTF-8")));
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
所以这里是我所得到的例子:我尝试发送
GET/HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:65432
Origin: http://localhost
Sec-WebSocket-Key: ph1CO1PCF60uojeP+nql5A==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
和:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: Z2Vy9p7Lp+MZPdZOe+L5GhVBDpc=
我想指出,送我送头应该因为在我开发的PHP WebSocket服务器中,发送不超过这些头文件就可以工作。
行结束符必须是“\ r \ n”。 EOL只是一个混淆版本吗?另外,您是否以“\ r \ n \ r \ n”结束您的回复?这不会显示在您的代码中。 你写过WebSocket.getWebSocketKey()吗?如果你这样做,你可以发布它的代码吗? – simonc
我也尝试使用“\ r \ n”进行EOL。它在我的代码片段的第一行中定义。 – arik
EOL *必须*为“\ r \ n”。你可以尝试改变它,并在你的Sec-WebSocket-Accept头后添加“\ r \ n \ r \ n”吗? – simonc