问题的原因是,在客户机组件的生命周期内,实际上创建了多个套接字连接实例。
从服务器的角度来看
"new_message"
正在发送到在组件中创建的套接字
send
箭头功能。因为那个套接字实例不监听
“新消息”
,因此不会在控制台中看到预期的日志消息。
也许你可以考虑重构你的客户端组件代码,像这样连接一个单一的套接字,并把它作为发送和监听来自服务器的消息的单一方式?
class YourComponent extends Component {
// Add socket field to component class
socket : ''
// Note that the send method is not an arrow function here, so
// care should be taken to consider how you invoke send() if
// your current implementation relies on this being an arrow function
function send(e) {
e.preventDefault();
const socket = this.state.socket // UPDATE: Access socket via state
// Send messages to server via the same socket instance of this class
if(socket) {
socket.emit("message", () => {
message: "hey !"
})
console.log("send ended")
}
}
function componentDidMount(){
const socket = io.connect(this.state.endpoint)
socket.on("new_message", (message) => {
console.log("new message ", message)
})
socket.on("user_connected", (message) => {
console.log(message)
})
// UPDATE: Connect the socket, and hold a reference for reuse by the component class
// instance via the component's state (seeing you can't add a class field for this)
this.setState({ socket : socket })
}
}