您好我想使用以下对象将userID,userName和socketId存储到users数组中:
var userInfo = new Object();
userInfo.userName = user.userName;
userInfo.userId = user.userId;
userInfo.socketId = socket.id;
users.push(userInfo);
我使用此示例link创建了此对象。
现在我想显示这个对象值(userName,userId,socketId)如何在客户端显示这些值?
我不知道请帮帮我
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var users = [];
var roomName;
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('create', function (channel) {
socket.join(channel);
roomName=channel;
socket.channel=channel;
console.log('room', roomName);
});
socket.on('addUser', function (user) {
var userInfo = new Object();
userInfo.userName = user.userName;
userInfo.userId = user.userId;
userInfo.socketId = socket.id;
users.push(userInfo);
updateClients();
});
socket.on('chat message', function(msg){
});
socket.on('disconnect', function(){
});
function updateClients() {
io.to(socket.channel).emit('update', users);
console.log('users list is ', users);
}
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
答案 0 :(得分:3)
我想了解你的要求,之后我想分享一些片段。
获取'addUser'触发器后,您需要将userinfo推送到数组中,同时需要为客户端发射。
<强> // server.js 强>
socket.on('addUser', function (user) {
var userInfo = new Object();
userInfo.userName = user.userName;
userInfo.userId = user.userId;
userInfo.socketId = socket.id;
users.push(userInfo);
updateClients(users);
});
function updateClients(usersInfo) {
//io.emit('update', usersInfo);
io.to(socket.channel).emit('update', usersInfo);
console.log('users list is ', users);
}
<强> //客户端强>
var socket = io(); // in client.html
var socket = require("socket.io")(http); // in client.js
socket.on('update',function(usersInfo){
usersInfo.forEach(function(single_user){
//now you can use userinfo object according to your requirement
});
});
用户触发的用户的发射数据。所以你需要理解socket.io
的.on和.emit