Socket.on is not firing



我正在构建一个留言板作为学习练习,并有工作通知和一个可与socket.io.一起使用的聊天应用程序

我正在尝试集成一个基本的视频通话功能,但我对该功能的一些基本准备工作感到困惑。当服务器发出相关函数时,我的socket.on代码没有启动,我不知道为什么。发射周围的控制台日志都在执行,所以我知道代码正在被访问。

在客户端上,我的socket.On代码与我的通知位于同一个组件中,它们正在工作,并且肯定已安装。

是userOff和receiveCall函数没有被执行(无论出于何种原因(。。。

任何帮助都将不胜感激。

服务器:

io.on('connection', (socket) => {
socket.emit('messageFromServer');
socket.on('messageToServer', (dataFromClient) => {
connectedUsers[dataFromClient.username] = socket;
});
socket.on('join', ({ username, room }) => {
socket.join(room);
socket.emit('message', 'Welcome!');
socket.broadcast
.to(room)
.emit('message', `${username} has joined the room!`);
});
socket.on('messageRoom', ({ username, room, message }) => {
socket.broadcast.to(room).emit('message', `${username}: ${message}`);
});
socket.on('call', ({ username, id }) => {
if (connectedUsers[username]) {
connectedUsers[username].emit('recieveCall', id);
console.log('online emitted');
} else {
socket.emit('userOff');
console.log('offline emitted');
}
});
socket.on('disconnect', () => {
socket.disconnect(true);
});
});

客户端:

import React, { useContext, useEffect } from 'react';
import socketIOClient from 'socket.io-client';
import StateContext from '../StateContext';
import DispatchContext from '../DispatchContext';
const endpoint = 'http://localhost:5000';
const Socket = () => {
const appState = useContext(StateContext);
const appDispatch = useContext(DispatchContext);
const socket = socketIOClient(endpoint);
useEffect(() => {
socket.on('messageFromServer', () => {
socket.emit('messageToServer', { username: appState.username });
});
socket.on('userOff', () => {
console.log('user offline');
});
socket.on('recieveCall', (id) => {
console.log('recieve call');
});
socket.on('mailNotification', () => {
document.getElementById('notifyMail').classList.add('notify');
});
socket.on('boardsNotification', () => {
document.getElementById('notifyBoards').classList.add('notify');
});
}, []);
return null;
};
export default Socket;

您是否尝试调用socket.open first

https://socket.io/docs/client-api/#socketopen

并监听连接事件

https://socket.io/docs/client-api/#Event-%E2%80%98连接%E2%80%99

最新更新