我通过服务器将数据从客户端发送到客户端有点麻烦(以避免监听客户端上的端口)。
我有这样的服务器:
var net = require("net");
var server = net.createServer(function(socket) {
socket.on("data", function(data) {
});
});
server.listen(port);
现在,我想通过服务器将数据从一个客户端重定向到另一客户端。但是我不知道如何执行此操作,因为我不知道如何从另一个连接中获取一个连接。
有谁知道我该怎么做?
您可以将所有客户端保存在一个简单的数组中,然后将其发送到每个客户端,而无需客户端的套接字ID。因此每个客户只会得到所有其他客户。那么您可以通过客户ID来解决:
var net = require("net");
var clients = {};
var server = net.createServer(function(socket) {
socket.on("connect", function ()
{
// Get the socket id of the connected client
var socketId = null;
// Get the client socket
var clientSocket = null;
clients[socketId] = clientSocket;
});
// Socket is the client
socket.on("data", function(data) {
var d = JSON.parse(data);
if (d.client)
{
if (!clients[d.client.id])
{
// Client doesn't exists
return;
}
// Send messages to the client with the saved socket
clients[d.client.id].send(d.data);
}
});
socket.on("end", function ()
{
// Get the socket id of the disconnected client
var socketId = null;
delete clients[socketId];
});
});
server.listen(port);
我知道可以使用socket.io,因此强烈建议您也使用它。
在socket.io中,可能看起来像这样:
var io = require('socket.io')(80);
// Store all your clients
var clients = {};
// Example: http://socket.io/docs/#using-with-node-http-server
io.on("connection", function (socket)
{
// Save the client to let other client use it
clients[socket.id] = socket;
// Send all the clients except the self client
sendClient(socket);
// Client disconnected or connection somehow lost
socket.on("disconnect", function ()
{
// Remove the client
delete clients[socket.id];
});
// Simple event to proxy to another client
socket.on("proxy", function (client)
{
if (clients[client.id])
clients[client.id].emit("event", client.data);
});
});
// Send all the clients and exclude the given socket id
function sendClient(socket)
{
var list = [];
for (let socketId in clients)
{
if (!clients.hasOwnProperty(socketId))
continue;
if (socketId == socket.id)
continue;
list.push(socketId);
}
socket.emit("clients", list);
}
客户端可以是(使用socket-io.client):
var io = require('socket.io-client');
var socket = io("http://localhost:80");
socket.on("connect", function ()
{
});
socket.on("clients", function (clients)
{
// We have all the clients
clients.forEach(function (clientId)
{
var client = {};
client.id = clientId;
client.data = {blah: 1};
socket.emit("proxy", client);
});
});
socket.on("disconnect", function ()
{
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句