Re: [sockjs] Uncaught Error: INVALID_STATE_ERR: sending initial msg only after connection

2,627 views
Skip to first unread message
Message has been deleted

Marek Majkowski

unread,
Oct 22, 2012, 10:42:27 AM10/22/12
to mrtn...@gmail.com, soc...@googlegroups.com
On Mon, Oct 22, 2012 at 2:06 PM, mrtn <mrtn...@gmail.com> wrote:
> I get Uncaught Error: INVALID_STATE_ERR when I run the following within a
> closure:
>
> function connect() {
> var options = {protocols_whitelist: ["websocket", "xhr-streaming",
> "xhr-polling", "iframe-htmlfile", "iframe-xhr-polling",
> "iframe-eventsource"], debug: true};
> conn = new SockJS("http://www.playmymodel.com/sockjs/wait", options);
> conn.onopen = function() { console.log("connected"); };
>
> ...
> }
>
> connect();
>
> if (conn != null) {
> var initialMsg = JSON.stringify({"subject": "hello", "content": "hello
> world"});
> conn.send(initialMsg);
> console.log("initial msg sent");
> }
>
> I suspect that the problem is that I send the msg too soon before the
> connection is fully established.

Correct. You can't call 'send' before onopen event is fired or after
'onclose' event.

> So how can I programmatically make sure
> that I send the first msg only after the connection is fully established
> (i.e. after 'onopen' callback is executed)?

Option #1: install onopen handler and do 'send' in it
Option #2: verify if 'conn.readyState' == SockJS.OPEN

> P.S. I want the 'initialMsg' to be sent automatically after the page is
> loaded in the browser, so a solution involving manual control of sending the
> msg is not suitable for this case.

Beware - establishing sockjs connection may take longer than loading
your page.

Marek

mrtn

unread,
Oct 22, 2012, 2:21:18 PM10/22/12
to soc...@googlegroups.com, mrtn...@gmail.com
Option #1: install onopen handler and do 'send' in it 
Option #2: verify if 'conn.readyState' == SockJS.OPEN 

Hi Marek,

About the first option, you mean something like this?

conn = new SockJS("http://mysite.com/sockjs", options);
conn.onopen = function() { console.log("connected");
var initialMsg = JSON.stringify({"subject": "hello", "content": "hello world"});
conn.send(initialMsg);
console.log("initial msg sent");
};

However, I've just tried that, and strange thing happened that the backend seemed never received the 'initialMsg' msg even though I can see 'initial msg sent' in the browser console log. Any idea? 

Marek Majkowski

unread,
Oct 22, 2012, 8:23:55 PM10/22/12
to mrtn...@gmail.com, soc...@googlegroups.com
No, this is a perfectly valid code. You must be doing something wrong.
(at the server side?) Take a look at our examples, maybe they'll
inspire you:
https://github.com/sockjs/sockjs-node/tree/master/examples

Marek

Shashwat Srivastava

unread,
Oct 23, 2012, 3:37:30 AM10/23/12
to soc...@googlegroups.com, mrtn...@gmail.com
Even I was getting this error (at times). Now I understand why. 

Thanks Marek :D

Shashwat
Reply all
Reply to author
Forward
0 new messages