2016-12-08 141 views
0

你好,我是想發出使用SOCKET命令用戶時設置被通過一些API改變.. 但我不知道我怎樣才能插座或插座告訴發出該消息給用戶.. 請幫助兩個模塊之間溝通的NodeJS

這是我的代碼

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

回答

0

你必須讓套接字'聽'在服務器上。例如,我使用的是表達對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); 
}); 
+0

嗨,我所做的一切,它在Socket類的constructor.i didnt只是提到它BCZ會使代碼更難以閱讀 – Rohit