views:

69

answers:

1

I have a site hosted at localhost:8000. Now, I have a server listening for websocket connections at localhost:8001. I would like my website to connect to this server through the websocket api like

var conn = new WebSocket('ws://localhost:8001');

But I get some errors in Chromium 6.0.472.62 upon calling

conn.send('something'); 

That looks like: Uncaught Error: INVALID_STATE_ERR: DOM Exception 11.

In Firefox 4 (4.0b8pre), I get the error: An attempt was made to use an object that is not, or is no longer, usable" code: "11

I thought this was an issue with the handshake not supporting websocket draft76 on the server, but I am using http://github.com/miksago/node-websocket-server/tree/master/lib/ws/ which claims to support draft75 and draft76.

Also, the initial handshake seems to work fine. I can receive a response from the server upon creating the new WebSocket, however, the problems arise on the call to "send" from the client side.

Is this an issue with the same origin policy since my httpserver is on port 8000 and the websocket server is on 8001? If so, how can I work around this?

A: 

Perhaps you need to wait for the onopen event to fire?

var conn = new WebSocket('ws://localhost:8001');
conn.onopen = function (e) {
    conn.send('something');
}
conn.onmessage = function (e) {
    console.log('got something: ' + e.data);
}

Also, it's a good idea to hook the onclose and onerror events too.

kanaka