我在reactjs和nodejs上使用socket io。我要做的是,将特定患者的信息发送给特定医生。从患者发送的消息应仅发送给患者已发送给该医生的消息,而不应发送给所有医生。就我而言,最多只能join
个事件被监听,但是无法向特定医生发射JoinAccept
。为此,我在服务器和客户端上所做的都是
server.js
io.of("/sockets").on("connection", socket => {
console.log("socket connection is made!!!", socket.id);
socket.on("Join", data => {
const msg = {
message: "I am joining"
};
io.in(data.to).emit("JoinAccept", msg);
});
}
客户端
socket.js
import React from "react";
import io from "socket.io-client";
import { SOCKET_URL } from "constants/url";
const SocketContext = React.createContext();
const SocketProvider = ({ children }) => {
const [socketClient, setSocketClient] = React.useState();
React.useEffect(() => {
const socket = io(SOCKET_URL);
setSocketClient(socket);
return () => {
io.disconnect();
};
}, []);
console.log("socketClient", socketClient);
return (
<>
<SocketContext.Provider value={{ socket: socketClient }}>
{children}
</SocketContext.Provider>
</>
);
};
export { SocketContext, SocketProvider };
patient.js
const Patient = () => {
const { socket } = React.useContext(SocketContext);
React.useEffect(() => {
const data = {
to: "doctorabc@gmail.com",
from: "patientabc@gmail.com",
message: "Join Me"
};
socket.emit("Join", data);
}, []);
return (
<div>
<h1>Patient</h1>
</div>
);
};
export default Patient;
Doctor.js
const Doctor = () => {
const [msg, setMessage] = React.useState("");
const { socket } = React.useContext(SocketContext);
const data = {};
React.useEffect(() => {
if (socket !== undefined) {
console.log("socket join", socket);
// this is not listened
socket.on("JoinAccept", message => {
debugger;
console.log("message", message);
setMessage(message);
});
}
}, [msg, socket]);
return (
<>
<h1>Doctor</h1>
</>
);
};
export default Doctor;
关于Doctor.js事件
socket.on("JoinAccept", message => {
debugger;
console.log("message", message);
setMessage(message);
});
未收听