1

I have written a simple client-server app where the client uses WebSocket in Javascript and the server uses the Jetty library for WebSocket. This is the server code that handles messages from the client:

@OnWebSocketConnect
    public void onConnect(Session session) {

        System.out.println("Connected");
    }

    @OnWebSocketMessage
    public void onMessage(String message) {
        System.out.println(message);
    }

and this is the code of the client when sending messages:

function Search() {
"use strict";
sender = new WebSocket("ws://localhost:8080");
sender.send("Hello server");
sender.close();
}

So when I call the "Search" function the output of the server is this:

Server output

Which means line sender.send("Hello server"); was not executed.

But when I insert alert("connected"); after sender = new WebSocket("ws://localhost:8080"); this is the new output:

New output

I have read the documentation about send() but it does not address this issue. Do you have any ideas why this happens?

1 Answer 1

3

You're not waiting for the connection to actually open. The reason it works with alert() is that you gain time for the socket to finish connecting.

Try this:

sender = new WebSocket(...)

sender.onopen = function() {
  sender.send('Hello server')
  sender.close()
}

The function you set as onopen will be executed when the connection is ready to send and receive data.

Why?

When you do new WebSocket(), Javascript doesn't wait until the socket is fully connected before moving on to the next line of code. The connection is just scheduled to happen.

This is unlike Java, the other language you're using, where execution usually blocks before moving on.

In your piece, you call close() immediately after creating the socket. This won't connect and then disconnect. The connection will never complete, since you only scheduled a connection and immediately cancelled it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your reply. I have used this method before but it seems the send() function only works inside onopen(). For example, when executing this code: function Search() { "use strict"; sender = new WebSocket("ws://localhost:8080"); sender.onopen=function() { sender.send("Hello Server!"); }; sender.send("Hello again!"); sender.close(); } the lines after onopen() should execute since the connection is established, but that's not the case. Are messages supposed to be sent only from inside onopen()? Thanks again
Slightly late but if someone is seeing this later and wondering the same question as @Captain_Rookie yes .onopen() is async so it executes whenever it has to when all of the conditions are met. (over simplification but you should get the point)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.