[英]Socket.io node.js socket.emit not working
I basically have a Node.js server, which acts as a middleman between two other servers. 我基本上有一个Node.js服务器,它充当其他两个服务器之间的中间人。
I am wondering if its possible to do something like this: 我想知道是否有可能做这样的事情:
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'
});
}
}
This "server" is both a server and a client. 该“服务器”既是服务器又是客户端。 Given that this server receives a message 'ev001', I want to forward another message onwards to another server.
鉴于此服务器收到消息“ ev001”,我想将另一条消息转发到另一台服务器。
So it becomes something like: 这样就变成了:
Server A -> ev001 -> This server (B) -> start -> Server C 服务器A-> ev001->此服务器(B)->启动->服务器C
Can you call a socket#emit() function outside of that socket's own "socket#on()" function? 您可以在该套接字自己的“ socket#on()”函数之外调用socket#emit()函数吗?
Yes, that's possible. 是的,那是可能的。
Here's a standalone version (which creates a server listening on 5040, much like the remote server that you're connecting to, and also a server on 5030, much like your "Matchmaking server" ): 这是一个独立的版本(它创建一个在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.