最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get details of the user that sent data (.emit()) to nodejs server? - Stack Overflow

programmeradmin3浏览0评论

I'm experimenting on an app that is running with nodejs, express and socket.io

Server Side:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

    socket.on('send_stuff', function(stuff){

        io.emit('log_stuff',newStuff);

    });

});

http.listen(54123, function(){
    console.log('listening on *:54123');
});

Client Side:

var socket = io.connect(':12345');
socket.emit('send_stuff',stuff);

My question is How do I get the details of the client (ip,user-agent,etc.) that executed socket.emit('send_stuff',stuff)?

I want to pass it to the newStuff variable.

socket.on('send_stuff', function(stuff){}); in this line stuff only returns the value that was send by client emit().

Any ideas how to do this?

I'm experimenting on an app that is running with nodejs, express and socket.io

Server Side:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

    socket.on('send_stuff', function(stuff){

        io.emit('log_stuff',newStuff);

    });

});

http.listen(54123, function(){
    console.log('listening on *:54123');
});

Client Side:

var socket = io.connect('http://example.:12345');
socket.emit('send_stuff',stuff);

My question is How do I get the details of the client (ip,user-agent,etc.) that executed socket.emit('send_stuff',stuff)?

I want to pass it to the newStuff variable.

socket.on('send_stuff', function(stuff){}); in this line stuff only returns the value that was send by client emit().

Any ideas how to do this?

Share Improve this question edited Aug 15, 2014 at 7:59 Joe asked Aug 15, 2014 at 7:47 JoeJoe 8,28214 gold badges60 silver badges96 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 17

You can get client's ip and user-agent in connection event.

io.on('connection', function(socket){
  console.log("ip: "+socket.request.connection.remoteAddress);
  console.log("user-agent: "+socket.request.headers['user-agent']);
})

Documentation can give you some hints http://socket.io/docs/server-api/

This worked for me:

io.on('connection', function(socket) {
    var userAgent = socket.handshake.headers["user-agent"];
    console.log("User-Agent: " + userAgent);
});
发布评论

评论列表(0)

  1. 暂无评论