在两个模块nodejs之间进行通信

时间:2016-12-08 09:14:29

标签: javascript node.js sockets

您好我正在尝试使用 SOCKET 向用户发出命令,当通过某些 API 更改设置时。 。 但我不知道如何获得套接字或告诉套接字向用户发送消息.. 请帮忙

这是我的代码

//Socket INIT
  
class Socket{
 constructor(){
    
 //Init variables
  }
  start(){
 //Start socket
   this.io.use((socket, next) => this.auth.authDevice(socket, next));
  this.io.on('connection',(socket) => this.conn.handleConn(socket));

  }
  
}

//Socket Connection
let socketStack = [];
class Connection{
   handleConn(socket){
     //  store client 
     socketStack[socket.userid] = socket
   }
    pushCmd(userid, command){
      //cheeck if userid exists in >>socketStack<<  and emit 
    }
 }

//Command Emit 
class Command {
  constructor(id) {
    this.userid = id.userid
    //socket - Connection class
    this.socketConn = new SocketHandler()
  }
  static push(userid, command) {
    
    //i want to sent it to current socket context. this has empty socketStack..
  this.socketConn.pushCmd(userid, command);
  }
}
let socket = new Socket();


socket.start() //connection started, all clients connect to //this  socket .. I WANT API to use this socket to emit something that //API sends....

1 个答案:

答案 0 :(得分:-1)

你必须设置插座才能听到&#39;在服务器上。例如,我使用express与node.js,这是我运行socket.io的方式:

var app = express();
var server = require('http').createServer(app);

var io = socketio.listen(server);

io.on('connect', function (socket) {
    socket.on('exampleCall', function () {
        console.log("socket invoked!");
        socket.emit("exampleEmit");
    });
});

server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function () {
var addr = server.address();
console.log("Server listening at", addr.address + ":" + addr.port);
});