WebSocket onpen函数不工作

WebSocket onpen function not working

本文关键字:工作 函数 onpen WebSocket      更新时间:2023-09-26

我正在通过web套接字向Java服务器发送文本,但onpen函数从未被调用——这是客户端使用的函数(WebSocketTest),当我关闭服务器时,onclose函数的警报消息会被正确地调用

function WebSocketTest()
{
  if ("WebSocket" in window)
  {
     alert("WebSocket is supported by your Browser!");
     // Let us open a web socket
     var ws = new WebSocket("ws://localhost:4444");
     ws.onopen = function()
     {
        // Web Socket is connected, send data using send()
        ws.send("Message to send");
        alert("Message is sent...");
     };
     ws.onmessage = function (evt) 
     { 
        var received_msg = evt.data;
        alert("Message is received...");
     };
     ws.onclose = function()
     { 
        // websocket is closed.
        alert("Connection is closed..."); 
     };
  }
  else
  {
     // The browser doesn't support WebSocket
     alert("WebSocket NOT supported by your Browser!");
  }
}

这是我在服务器上收到的

GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:4444
Origin: null
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: 4BAiV8AU80juonjYQw5V9g==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko)      Chrome/31.0.1650.63 Safari/537.36

这是服务器端

public class InvoiceListener {
    private static BufferedReader in;
    private final static int port = 4444;
    private static ServerSocket listenSocket;
    private static Socket client;
    private static Invoice invoice;
    private static String info;
    public static void main(String[] args) throws IOException {
        PrintInvoice printer;
        ServerSocket listenSocket = new ServerSocket(port);

            System.out.println("Listening");
            client = listenSocket.accept();
            System.out.println("client connected !");
            in = new BufferedReader(new InputStreamReader(
                    client.getInputStream()));
            while ((info = in.readLine()) != null) {
                System.out.println(info);
            }
    }
}

您不能将ServerSocket与web套接字一起使用,您需要有一个支持侦听web套接字调用的web服务器,您可以在此处查看支持的web服务器。

支持的web套接字java服务器:

  • http://jwebsocket.org/
  • http://tomcat.apache.org/
  • http://eclipse.org/jetty/
  • http://grizzly.java.net/
  • http://www.caucho.com/resin-web-server/

哪些流行的Web服务器支持HTML5WebSocket?

好的,我找到了解决方案,似乎收到的日期实际上是由于握手协议

GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:4444
Origin: null
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: 4BAiV8AU80juonjYQw5V9g==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko)

并且我必须再次从服务器向客户端发送响应以启动连接,这就是Onopen函数工作的时候