[Jslib] Problem using new socket code

Stephen Knight stknight at ultralifebatteries.com
Fri Apr 8 18:03:39 EDT 2005

Loren Peace wrote:
> I've recently gone back to a XUL app I was working on and am having trouble
> getting it to work with the new socket code and would appreciate any help.
> I think my problem is that I need to send a greeting message when 
> connecting
> and get back a reply from that.  The open, write, and read are all in the
> same function (connect).  The problem appears to be that the new socket
> code relies on its new isAlive method which has a note above it about not
> working in the same JavaScript stack crawl as open.  Now I'm not sure I
> understand what that means but I believe that means I can't write or read
> in the same Javascript invocation (response to user action) as the open
> call?  Is that a correct understanding?  If so, any suggestions on how
> to work around this problem?
> Oh and the socket.xul sample works fine so the socket code itself is 
> working
> for my platform; but I note that it does open and reading/writing in
> response to different user actions and would not face the problem
> (based on my above listed understanding of it.)

I used the term "stack crawl" in an attempt to describe the chain of javascript function calls 
that's invoked to handle an event.

So, if you do the following as a response to a key-press (for example):

<button onkeypress="do_something();"/>

function do_something()
   // stuff

function do_socket()
   var aSocket = new Socket();

The aSocket.write will fail.  The socket.xul example has open occuring during a different "stack 
crawl" since different buttons cause the socket-functions to be invoked.

As far as I can tell, this is a limitation of Javascript/XUL/Mozilla.  Either isAlive isn't reliable 
  because the socket-open hasn't actually occurred or the socket state doesn't settle down until 
returning out of the application-specific javascript.

One trick I've done is to use setTimeout() to get around this.  Ex:

function openConnection( doOpen )
   if( doOpen )
       setTimeout( "openConnection( false );", 200 );
       gSocket.write(...);   // send greeting here
       gSocket.read(...);    // get reply

Hope this helps.

Stephen Knight
Ultralife Batteries, Inc.

More information about the Jslib mailing list