gpt4 book ai didi

node.js - NodeJS : Client to Client via Server

转载 作者:太空宇宙 更新时间:2023-11-04 02:19:12 26 4
gpt4 key购买 nike

我在通过服务器从客户端向客户端发送数据时遇到了一些问题(以避免监听客户端上的端口)。

我有一个这样的服务器:

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 ()
{

});

关于node.js - NodeJS : Client to Client via Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34251942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com