简体   繁体   中英

Socket.IO: How to communicate/exchange data between socket.on() event in the same server?

I have certain line of code written under one socket.on event which is being called from client side to get the data using callback mechanism.
Is it possible to communicate between two socket.on event and exchange the data using callback within the same server and same file ?

For. eg A normal flow between client and server:

socket.emit('init',data,function(callbackFromServer)) //from client
          |      ^
          |      | server respond through callback to client
          V      |
socket.on('init',function(data, callback){/*....*/});  // to server  

I want to implement same case, but within server itself between two socket.on() event, to exchange the data. ie:

                         client  
                          |  ^
                          V  |
      socket.on('someEvent',function(data,callback1){/*....*/}) // some.js
                          |  ^
                          V  | // <-- I want to achieve this
      socket.on('init',function(data,callback2){/*.....*/})     // some.js

Is it possible to achieve this, by any approach ?

I'm not sure if I understood the use-case completely, but if you just want to call the other function, why don't you use variables to reference those functions? You can then call them whenever you want.

var someEventFn = function(data, callback1) {
        initFn(data, function(result) {
            // here you have the result from the init method
        });
    },
    initFn = function(data, callback2) {
        // some js
    };

socket.on('someEvent', someEventFn);
socket.on('init', initFn);

Then you can call initFn from inside someEventFn while still allowing it to be called in the socket.on event. Did I understand your question correctly?

Create another socket io client in server side, and then call the function using that client.

var socket = io.connect('http://localhost:port');
socket.on('connect', function () {  
  socket.emit('another function', { param1: 'value1' });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM