Websocket.onmessage没有触发

时间:2019-10-09 12:34:52

标签: javascript java websocket

我尝试通过JS-WebSocket在Java WebsocketServer(LINQ queries are no longer evaluated on the client)与网页之间进行通信。

我的JS-Websocket:

window.websocket = new WebSocket("ws://localhost:8000");
window.websocket.onopen = () => {
    window.websocket.send("Hello")
}




window.websocket.onmmessage = function(event) {
    alert('Hi');

    console.log(event.data);
}

和我的Java Websocket-Server:

package test;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

public class testsocket extends WebSocketServer {


    private static int TCP_PORT = 9000;

    private Set<WebSocket> conns;

    public testsocket() throws UnknownHostException {
        super(new InetSocketAddress(TCP_PORT));
        conns = new HashSet<>();

    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conns.add(conn);
        System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());

    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {

    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println(message);

        String s2send = "hello";
        System.out.println(s2send);
        conn.send(s2send);


    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        ex.printStackTrace();
        if (conn != null) {
            conns.remove(conn);
            // do some thing if required
        }

    }

}

因此,我的Java-Websocket打印“ Hello”,以便可以从JS到Java进行通信,但是另一方面,我的Websocket既未显示警报也未在控制台中打印,因此我假设onmessage不会触发

1 个答案:

答案 0 :(得分:1)

如果确定,您的Java ws服务器正在运行...那么

有一个错字!事件侦听器应为window.websocket.onmessage window.websocket.onmmessage。两个“ m”:)

window.websocket = new WebSocket("ws://localhost:8000");
      window.websocket.onopen = () => {
        window.websocket.send("Hello");
      };

      window.websocket.onmessage = function(event) {
        alert("Hi");

        console.log(event.data);
      };