我的WebSocket没有按预期工作; 服务器用Java实现,客户端用JavaScript实现

Ben*_*Ben 1 javascript java html5 utf-8 websocket

我似乎无法在Java服务器和JavaScript客户端之间建立"正确"连接.它似乎连接好了,客户端发送它的标题好吧,但这是它得到的.onopen或者onmessage根本不会触发这些功能.

这是Java服务器的代码:

import java.net.*;
import java.io.*;
public class Server {
    static DataOutputStream out;
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8112);
            System.out.println("Server Started");
            while(true) {
            Socket socket = serverSocket.accept();
            System.out.println("A client connected");
            out = new DataOutputStream(socket.getOutputStream());

            //Send a simple-as-can-be handshake encoded with UTF-8
            String handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r" +
            "Upgrade: WebSocket\r" +
            "Connection: Upgrade\r" +
            "WebSocket-Origin: http://localhost\r" +
            "WebSocket-Location: ws://localhost:8112/\r" +
            "WebSocket-Protocol: sample\r\n\r\n";
            out.write(handshake.getBytes("UTF8"));
            System.out.println("Handshake sent.");

            //Send message 'HI!' encoded with UTF-8
            String message = "HI!";
            out.write(0x00);
            out.write(message.getBytes("UTF8"));
            out.write(0xff);
            System.out.println("Message sent!");

            //Cleanup
            socket.close();
            out.close();
            System.out.println("Everything closed!");
        }
    } catch(Exception e) {
        System.out.println(e.getMessage());
    }
}
Run Code Online (Sandbox Code Playgroud)

这是客户端的代码:

<html>
  <head>
    <meta charset="UTF-8">
    <script>
      function load() {
        var ssocket = new WebSocket("ws://localhost:8112/");
        socket.onopen = function(e) { alert("opened"); }
        socket.onclose = function(e) { alert("closed"); }
        socket.onmessage = function(e) { alert(e.data); }
      }
    </script>
  </head>
    <body onload="load();">
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

为什么不会onopenonmessage触发?我尝试过很多不同的东西,我似乎无法做到.

我究竟做错了什么?

Sim*_*onJ 5

您似乎缺少协议的挑战 - 响应方面 - 客户端发送两个额外的标头和一些随机数据:

GET /demo HTTP/1.1
Host: example.com
Connection: Upgrade
Sec-WebSocket-Key2: 12998 5 Y3 1  .P00
Sec-WebSocket-Protocol: sample
Upgrade: WebSocket
Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5
Origin: http://example.com

^n:ds[4U

并且服务器应该通过以下方式获得MD5响应:

  • 从每个密钥中提取数字(4146546015,1299853100)
  • 除以键中的空格数
  • 将键序列化为4字节整数,与数据连接
  • 计算MD5摘要

产生如下响应:

HTTP/1.1 101 WebSocket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Origin: http://example.com
Sec-WebSocket-Location: ws://example.com/demo
Sec-WebSocket-Protocol: sample

8jKS'y:G*Co,Wxa-

此过程旨在防止WebSocket服务器处理非WebSocket请求 - 有关详细信息,请参阅WebSocket协议的第1.3节.