1

I was trying to make a Read\Write function for websocket but i've a problem...

var inarrivo = 0;
var risposta = "";

function RDW_Command(Stringa) {
    var Risposta = "";
    Stringa = "$" + Stringa;
    socket.send(Stringa);
    inarrivo = 0;
    while (inarrivo == 0) {
        doNothing();
    }
    return risposta;
}

function doNothing() {}
socket.onmessage = function (msg) {
    risposta = msg.data;
    inarrivo = 1;
};

The problem is that it freeze when it enter in the while loop.... Any idea to fix it? >.< thank you!! Andrea

1
  • Javascript is all about asynchronous function calls. You should read into this. You can't sleeps thread like you are used to from other languages. Commented Jun 21, 2012 at 13:05

2 Answers 2

8

You program websockets in javascript in the usual (in javascript) event/callback based way.

Here's an example :

var somePackage = {};
somePackage.connect = function()  {
    var ws = new WebSocket('ws://'+document.location.host+'/ws');
    ws.onopen = function() {
        console.log('ws connected');
        somePackage.ws = ws;
    };
    ws.onerror = function() {
        console.log('ws error');
    };
    ws.onclose = function() {
        console.log('ws closed');
    };
    ws.onmessage = function(msgevent) {
        var msg = JSON.parse(msgevent.data);
        console.log('in :', msg);
        // message received, do something
    };
};

somePackage.send = function(msg) {
    if (!this.ws) {
        console.log('no connection');
        return;
    }
    console.log('out:', msg)
    this.ws.send(window.JSON.stringify(msg));
};

You call somePackage.connect to open the connection. After that, the message arrivals are handled in the onmessage handler and to send a message to the server you just call somePackage.send.

Even if this is full of asynchronous calls, that doesn't mean that your program won't immediately react to the arrival of a message (as soon as your other functions have stopped working because you have only one thread).

Sign up to request clarification or add additional context in comments.

Comments

3

This is an infinite loop:

inarrivo = 0;
while (inarrivo == 0) {
    doNothing();
}

The solution is to remove the infinite loop.

4 Comments

the function: socket.onmessage = function (msg) { risposta = msg.data; inarrivo = 1; }; Should change inarrivo==1 when a message comes! >:
That function will never execute as the browser is busy executing the infinite loop...
so it's impossible make a read/write in that way? isnt there a command that exc other thread?
You only get one thread in javascript (well you can use WebWorkers but you still have to write async code), so no. Just use callbacks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.