如何解决Socket.on没有触发
我正在建立一个留言板作为学习练习,并具有可工作的通知和一个与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',room,message }) => {
socket.broadcast.to(room).emit('message',`${username}: ${message}`);
});
socket.on('call',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
https://socket.io/docs/client-api/#socketopen
并监听连接事件
https://socket.io/docs/client-api/#Event-%E2%80%98connect%E2%80%99
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。