im使用express和react和socket.io构建一个聊天应用程序,一切正常,除了当我从服务器发出消息时,它不会在客户端捕获消息。这是为什么?我的代码是:
index.js(服务器)
const io = require('socket.io')(server);
io.on('connection', socket => {
socket.on('join-room', data => {
console.log(`Joining room ${data.room}`);
socket.join(data.room);
});
socket.on('leave-room', data => {
console.log(`Leaving room room ${data.room}`);
socket.leave(data.room);
});
socket.on('new-message', data => {
console.log(`Sending message to room ${data.room}`);
socket.to(data.room).emit('new-message', data.message);
});
});
JoinRoom.js(反应)
useEffect(() => {
socket.on('new-message', data => {
console.log('getting new message');
setMessages([...messages, data]);
});
}, [messages]);
useEffect(() => {
socket.emit('join-room', { room: id });
async function fetchData() {
const response = await req.get('/api/room/' + id);
setRoom(response.data);
const _messages = await req.get('/api/messages/' + id);
setMessages(_messages.data.docs);
}
fetchData();
}, [id]);
const send = e => {
e.preventDefault();
socket.emit('new-message', {
room: id,
message: newMessage
});
const data = {
message: newMessage,
user: 'Mikolaj',
roomId: id
};
req.post('/api/messages/send', data);
setNewMessage('');
};