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).