我是反应新手。我想用react和socket.io建立一个群聊。但是当我尝试这样做时有一些困难。下面是我的代码示例。任何帮助将不胜感激。
Server.js
const io = require('socket.io')(http)
// Listen for a connection
// usernames which are currently connected to the chat
var usernames = {};
io.sockets.on('connection', function (socket) {
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function (room) {
// store the room name in the socket session for this client
socket.room = 'room1';
// send client to room 1
socket.join('room1');
console.log("join room1 " + room)
});
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
console.log("message " + JSON.stringify(data))
// console.log(socket);
socket.broadcast.in('room1').emit('updatechat', data);
});
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
socket.leave(socket.room);
});
})
Client.js
let name = "test"
socket.emit('adduser', name);
socket.emit("sendchat", message_text)
socket.on('updatechat', function (data) {
messages.push(data);
console.log("Hello!!!");
});
我想要做的是将短信添加到聊天板。我已经尝试了代码中的广播,并将其作为状态添加到react组件中。但是,它只能添加该特定用户的消息,我的代码出了什么问题?
答案 0 :(得分:0)
这里的主要问题是您使用socket.broadcast.in
除了发出广播的用户套接字之外发送给所有人,这反过来意味着一次只有一个客户端会收到消息。
旧功能
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
console.log("message " + JSON.stringify(data))
// console.log(socket);
socket.broadcast.in('room1').emit('updatechat', data);
});
新功能
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
console.log("message " + JSON.stringify(data))
// console.log(socket);
io.in('room1').emit('updatechat', data);
});
在示例中,我们尝试让特定room
内的所有人看到我们可以使用io.in('room').emit();
来实现我们所追求的目标的消息。