如何在我的服务器上连接所有IP连接?

时间:2017-05-15 18:06:39

标签: javascript websocket server ip

伙计们,我对javascript中的websockets有这个疑问,我想要将ip连接到服务器并且我没有想法这样做,我只想要ip' s ,我只想要那些现在连接的那些。

这是我的服务器:

var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
  console.log((new Date()) + ' Received request for ' + request.url);
  response.writeHead(404);
  response.end();
});
server.listen(8080, function() {
  console.log('Server is listening on port 8080');
});

wsServer = new WebSocketServer({
  httpServer: server,
  autoAcceptConnections: false
});

function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
  // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' request.origin + ' rejected.');
  return;
}

var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
    if (message.type === 'utf8') {
        console.log('Received Message: ' + message.utf8Data);
        var ipAddress = connection.remoteAddress;
        console.log(ipAddress);
        connection.sendUTF("pablo puta");
    }
    else if (message.type === 'binary') {
        console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
        connection.sendBytes(message.binaryData);
    }
});
connection.on('close', function(reasonCode, description) {
    console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
 });
});

拜托,如果你能帮助我,我将非常感激。

1 个答案:

答案 0 :(得分:3)

我相信你可以保留一个ips的对象:

var ips={};
connection.on('close', function(reasonCode, description) {
  delete ips[connection.remoteAddress];
});
 connection.on('open', function(reasonCode, description) {
    ips[connection.remoteAddress]=true;
});

然后以某种方式回应:

Object.keys(ips);

给自己......

(我相信它必须是 this 而不是处理程序中的 connection ,但我不是专家......)