【发布时间】:2019-07-04 04:43:37
【问题描述】:
我正在学习 Socket.IO,我正在尝试做一些非常简单的事情,在连接时从服务器向客户端发出一些文本(这可行),并从客户端向服务器发出信号(这不起作用)。 这是我的客户端代码(ReactJS 组件)
import React, { Component } from 'react';
const io = require('socket.io-client');
const socket = io.connect('http://x.x.x.x:xxxx');
class Client extends Component {
constructor(props) {
super(props);
this.state = {
String1: 'No text yet',
}
}
componentDidMount() {
socket.on("message", data => this.setState({ String1: data }));
{ socket.emit('Update', 'test') }
};
render() {
return (
<div>
String1 is: {this.state.String1}
</div>
);
}
}
export default Client;
这是我的服务器代码(NodeJS):
const server = require('http').createServer()
const io = require('socket.io')(server)
io.on('connection', function (socket) {
console.log('client connected');
socket.emit('message', 'You are connected');
io.on('Update', function(ttext){
console.log('Updated');
});
});
io.sockets.on("disconnect", () => console.log("Client disconnected"));
server.listen(3000, function (err) {
if (err) throw err
console.log('listening on port 3000')
})
客户端:在浏览器上,我正确地看到“还没有文本”,一旦客户端连接到服务器,它就会变为“您已连接”。
但是,在服务器端,每次客户端浏览器刷新时,我只能在终端上看到“客户端已连接”,但没有其他内容,没有“已更新”,也没有“客户端已断开连接”。
我做错了什么?
【问题讨论】: