![](/img/trans.png)
[英]socket.io in node.js: socket.emit doesn't complete before socket.disconnect
[英]Socket.io node.js socket.emit not working
我基本上有一個Node.js服務器,它充當其他兩個服務器之間的中間人。
我想知道是否有可能做這樣的事情:
let matchSocket = ioClient.connect('http://localhost:5040');
http.listen(5030, function () {
console.log('Matchmaking server is now running.');
});
matchSocket.on('connect', function () {
});
io.on('connection', function (socket) {
// Send event 'ev001' as a CLIENT
socket.on('ev001', function (data, callback) {
matchSocket.emit('start', {
message: 'message'
});
}
}
該“服務器”既是服務器又是客戶端。 鑒於此服務器收到消息“ ev001”,我想將另一條消息轉發到另一台服務器。
這樣就變成了:
服務器A-> ev001->此服務器(B)->啟動->服務器C
您可以在該套接字自己的“ socket#on()”函數之外調用socket#emit()函數嗎?
是的,那是可能的。
這是一個獨立的版本(它創建一個在5040上偵聽的服務器,就像您要連接的遠程服務器,在5030上的一個服務器,就像您的“配對服務器” ):
const ioServer = require('socket.io');
const ioClient = require('socket.io-client');
// Your remote server.
ioServer().listen(5040).on('connection', function(socket) {
socket.on('start', function(message) {
console.log('remote server received `start`', message);
});
});
// Connect to the "remote" server.
let matchSocket = ioClient('http://localhost:5040');
// Local server.
ioServer().listen(5030).on('connection', function(socket) {
// Send a message to the remote server when `ev001` is received.
socket.on('ev001', function(message) {
console.log('received `ev001`');
matchSocket.emit('start', { message: 'message' });
});
});
// Connect to the local server and emit the `ev001` message.
ioClient('http://localhost:5030').emit('ev001');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.