本文介绍了Socket.io 为 Socket 识别用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些代码示例,通过 socket.io 识别连接的用户......所以现在我必须在索引页面上写一个代码来与用户通信.

I write some code example that identifi connected users via socket.io... So now I must write a code on index page to comunicate with users.

代码如下以及如何向用户[1]欢迎"和用户[2]HI men"发送消息,并限制2个用户的连接.所以当 2 个用户连接时,其他人都无法连接..

The code is below and HOW to send a message to user[1] "Welcome" and for user[2] "HI men" and also limit connection fr 2 users. so when 2 user connected then anybody else cant connect..

Index.html:

Index.html:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect();
  var users;
  socket.on('hello', function (data) {
    console.log(data.hello);
  });
  socket.on('listing', function (data) {
     users = data;
  });
  socket.on('chat', function (message) {
     console.log(message);
  });
  socket.on('message', function (message) {
     console.log(message);
  });
  function chat (message) {
    socket.emit('chat', message);
  }
  function message (user, message) {
    socket.emit('message', {
       user: user,
       message: message
    });
  }
</script>

app.js

var express = require('express');
var app = express.createServer();
var io = require('socket.io').listen(app);

app.listen(3000);

app.use(express.static(__dirname));

var users = {};
var userNumber = 1;

function getUsers () {
   var userNames = [];
   for(var name in users) {
     if(users[name]) {
       userNames.push(name);
     }
   }
   return userNames;
}

io.sockets.on('connection', function (socket) {
  var myNumber = userNumber++;
  var myName = 'user#' + myNumber;
  users[myName] = socket;

  socket.emit('hello', { hello: myName });
  io.sockets.emit('listing', getUsers());

  socket.on('chat', function (message) {
    io.sockets.emit('chat', myName + ': ' + message);
  });
  socket.on('message', function (data) {
     users[data.user].emit('message', myName + '-> ' + data.message);
  });

  socket.on('disconnect', function () {
    users[myName] = null;
    io.sockets.emit('listing', getUsers());
  });
});

app.listen(process.env.PORT);

推荐答案

你可以先看看如何使用 Socket.io 配置授权.回调提供的 handshakeData 可以在那里修改(即:添加用户名属性),任何更改都可以通过 app.js 中的 socket.handshake 访问(通过传递给 io.sockets.on('connection',..) 回调的对象.使用也可从握手数据访问的请求标头信息,您可以在授权回调中设置用户值(即:来自数据库),以便您可以在 app.js 中识别给定套接字的用户.

You can start by taking a look at how to configure authorization with Socket.io. The handshakeData provided by the callback can be modified there (ie: add a username property), and any changes will be accessible via socket.handshake in your app.js (via the object passed in to the callback for io.sockets.on('connection',..). Using request header information that's also accessible from the handshakeData, you can set user values within the authorization callback (ie: from a database) so you can identify the user for the given socket in your app.js.

这是一个类似的例子

这篇关于Socket.io 为 Socket 识别用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 03:19