1

I try to communicate between a Java WebsocketServer (https://github.com/TooTallNate/Java-WebSocket) with an a Webpage via a JS-WebSocket.

My 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);
}

and my 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
        }

    }

}

So my Java-Websocket prints "Hello", so I can communicate from JS to Java, but on the other hand my Websocket is neither showing the alert nor printing in the console, so I assume onmessage isn't firing

1 Answer 1

2

If you are sure, your java ws server is working... Then

There is a typo! the event listener should be window.websocket.onmessage. NOT window.websocket.onmmessage. Two "m"s :)

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);
      };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.