Java WebSocket服务器OutputStream没有刷新

时间:2012-09-06 08:25:48

标签: java websocket outputstream flush no-data

我看过similar question,但我的问题没有解决。

为了学习,我正在尝试构建自己的Java WebSocket服务器。服务器设置正常,它接受传入连接并从客户端获取握手数据。然后我的服务器计算握手返回数据并尝试写入并刷新它。尽管如此,在Web检查器中,没有为客户端显示响应标头,onopen - 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服务器中,发送的只不过这些标题可以工作。

1 个答案:

答案 0 :(得分:3)

websocket握手是HTTP请求,后跟HTTP响应。 RFC2616声明HTTP的行结束标记是CRLF(“\ r \ n”)。

HTTP请求以双换行结束(“\ r \ n \ r \ n” - 请参阅RFC的第4节); websocket握手响应是一个HTTP响应,因此也需要像这样结束。