mgrstnr
mgrstnr

Reputation: 520

Send message through websocket using javascript

I am connecting to a WebSocket Server using javascript and the Play Framework. I am just having trouble understanding the proper way to make use of the websocket.send() method of the WebSocket.

 $(function() {

    //depending on the browser we have to use WebSocket or MozWebSocket
    var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
    var websocket = new WS('ws://localhost:9000/webSocket');

    websocket.onopen = function() {
        websocket.send('test');
    }
    //split the message from the websocket into type, user and text
    //uses a nifty regular expression
    websocket.onmessage = function (event) {
        $('.output').append(event.data);
    }
});

When I use send() outside the onopen event I get an error because send() is not available. I am just thinking that there must be another event to dynamically execute send() without the onopen event which (afaik) just executes when the connection opens up.

Thanks!

Upvotes: 0

Views: 418

Answers (1)

Patrick Evans
Patrick Evans

Reputation: 42736

onopen is the correct event handler to use as it is the handler that is used when the connection is ready to be used.

the api docs show only 4 event handlers onopen onmessage onerror onclose

Api doc

Upvotes: 1

Related Questions