Search code examples
javascriptnode.jssocket.ioappjs

How to communicate from server to client via sockets with nodejs?


Currently I am creating a Javascript application. I am using AppJS for this.

I have some problems understanding the connection between the client and server.

Menu bar -> socket problem

The problem is the menubar and sockets combination.

The socket connection

io.sockets.on('connection', onSocketConnection)

function onSocketConnection(socket) {
    socket.emit('onMessage', {
        date: new Date(),
        message: 'Welcome!'
    })
}

The menubar

var menubar = app.createMenu([{
    label:'File',
    submenu:[{
        label:'New',
        action: function() {
            // Simply window.reload() or windows.frame.reload()?    
            // Reload window
        }
    },{
        label:'Change something in view...',
        action: function() {
            // How to speak to client from here?
            // I cannot use socket.emit()
        }
    }, {
        label:'Exit',
        action: function() {
            window.close()
        }
    }]
}])

But how to tell the client when the user clicked on the menubar items?

Asynchronous long function -> sockets

Another problem using sockets is asynchronous long loading functions.

The socket connection

io.sockets.on('connection', onSocketConnection)

function onSocketConnection(socket) {
    var test = veryLongLoading()
    console.log(test) // undefined -.-'
    socket.emit('test', {
        test: test

    })
}

So I thought I need to use callbacks like this:

io.sockets.on('connection', onSocketConnection)

function onSocketConnection(socket) {
    veryLongLoading(returnValue)
}

function veryLongLoadingFunction(next) {
    // Blablabla
    next('test')
}

function returnValue(value) {
    // Again socket is not available -.-'
    socket.emit('test', {
        test: test
    })
}

Anyone faced the same problems or anyone who can point me into the right direction.

Maybe I just misunderstand the flow (I normaly program in PHP)


Solution

  • Problem 1

    For the first part, you need to listen to events from the server:

    socket.on('message-from-server', function(data) {
      // You need to trigger the sub-menu change here.
      // Which means you need a handle for the sub-menu object.
      subMenu.action(data)
    });
    

    Problem 2

    The pattern for long running async functions look like this:

    var veryLongLoading = function(next) {
       // pass your value to next
       // like this
       next(someValue);
    };
    

    Then to use it, you would do this:

    veryLongLoading(function(someValue) {
       socket.emit(someValue);
    });
    

    Hope that helps!