使用javascript通过websocket发送消息

时间:2013-07-31 10:05:10

标签: javascript websocket

我使用javascript和Play Framework连接到WebSocket服务器。我只是无法理解使用WebSocket的websocket.send()方法的正确方法。

 $(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);
    }
});

当我在send()事件之外使用onopen时,我收到错误,因为send()不可用。我只是想在没有send()事件的情况下动态执行onopen必须有另一个事件,而afaik只在连接打开时执行。

谢谢!

1 个答案:

答案 0 :(得分:1)

onopen是要使用的正确事件处理程序,因为它是准备好使用连接时使用的处理程序。

api文档仅显示4个事件处理程序 onopen onmessage onerror onclose

Api doc

相关问题