反応がある初心者です。また、私はreactとsocket.ioのグループチャットを設定したいと思います。しかし、それをやろうとするといくつかの困難があります。以下は私のコードサンプルです。どんな助けもありがとう。反応は反応とSocketioで失敗しました
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!!!");
});
チャットボードにテキストメッセージを追加することです。私はコードのような放送を試み、それを反応コンポーネントの状態として追加しました。ただし、その特定のユーザーのみがメッセージを追加できます。私のコードには何が問題なのですか?
お客様のクライアントコードでは、 'socket.emit(" sendchat "、message_text)'なし ';' –