Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Websockets Issue, Perhaps Same Origin Policy?

Tags:

html

websocket

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?

like image 309
Bain Markev Avatar asked Oct 13 '10 17:10

Bain Markev


People also ask

Does CORS affect WebSockets?

SOP/CORS does not apply to WebSocket, but browsers will send an origin header that contains the hostname of the server that served the HTML with the JS that opened the WebSocket connection. A WebSocket server can then restrict access by checking origin .

Is WebSocket cross-origin?

WebSockets can make cross-origin requests that are not restricted by browser-based protection mechanisms such as the Same Origin Policy (SOP) or Cross-Origin Resource Sharing (CORS). Without explicit origin validation, this makes CSRF attacks more powerful.

Why you should not use WebSocket?

Avoid using WebSockets if only a small number of messages will be sent or if the messaging is very infrequent. Unless the client must quickly receive or act upon updates, maintaining the open connection may be an unnecessary waste of resources.

What is WebSocket origin?

The WebSocket standard defines an Origin header field, which web browsers set to the URL that originates a WebSocket request. This can be used to differentiate between WebSocket connections from different hosts, or between those made from a browser and some other kind of network client.


1 Answers

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.

like image 140
kanaka Avatar answered Oct 21 '22 05:10

kanaka