本文介绍了在nodejs中区分黑白两个或更多个TCP客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是每个客户都有唯一的ID或什么东西吗?假设我要使用此回显服务器将从一个客户端收到的消息回显到所有连接的客户端:

var net = require('net');
var server = net.createServer();
server.on('connection', function (server_socket) {
    console.log('client connected');
    server_socket.write('hello client! Say something.');

    server_socket.pipe(server_socket);

    server_socket.on('end', function () {
        console.log('client disconnected');
    });
});

server.listen(80, 'localhost');
server.on('listen', function () {
    console.log('Listning for connections:');
});

server.on('error', function (error) {
    console.dir(error);
});

我尝试了我所知道的一切,即诸如连接,请求等事件.

解决方案

出于您的目的,您实际上并不需要UID,可以尝试将所有活动连接保留在一个数组中,并在需要时广播任何数据.

var connections = [];

server.on('connection', function (socket) {

    connections.push(socket);

    socket.write('SOMETHING');

    // Broadcast some message
    connections.forEach(function (connection) {
        if (connection !== socket) { // Filter connections
            connection.write('SOMETHING ELSE');
        }
    });

    // Clean up closed connections
    socket.on('close', function () {
        var index = connections.indexOf(socket); // Get socket index

        connections.splice(index, 1); // Remove the socket from the connections
    });
});

isn't there any Unique ID or something for every client?suppose I want use this echo server to echo message received from one client to all connected clients:

var net = require('net');
var server = net.createServer();
server.on('connection', function (server_socket) {
    console.log('client connected');
    server_socket.write('hello client! Say something.');

    server_socket.pipe(server_socket);

    server_socket.on('end', function () {
        console.log('client disconnected');
    });
});

server.listen(80, 'localhost');
server.on('listen', function () {
    console.log('Listning for connections:');
});

server.on('error', function (error) {
    console.dir(error);
});

I tried Everything i knew, i.eEvents like connection,request etc.

解决方案

For your purpose you do not really need of an UID, you can try to keep all the active connections in an array and broadcast any data when needed.

var connections = [];

server.on('connection', function (socket) {

    connections.push(socket);

    socket.write('SOMETHING');

    // Broadcast some message
    connections.forEach(function (connection) {
        if (connection !== socket) { // Filter connections
            connection.write('SOMETHING ELSE');
        }
    });

    // Clean up closed connections
    socket.on('close', function () {
        var index = connections.indexOf(socket); // Get socket index

        connections.splice(index, 1); // Remove the socket from the connections
    });
});

这篇关于在nodejs中区分黑白两个或更多个TCP客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:25