Socket.io 使用 Create-React-App - Connection_Refused 错误

Socket.io with Create-React-App - Connection_Refused Error

这是我第一次使用 Socket.io。我正在尝试将它引入一个由 create-react-app 引导的应用程序,但遇到了一些 ERR_CONNECTION_REFUSED 问题。

server.js

const io = require('socket.io')();
const port = 8000;

io.on('connection', (client) => {
  client.on('subscribeToTimer', (interval) => {
    console.log('client is subscribing to timer with interval ', interval);
    setInterval(() => {
      client.emit('timer', new Date());
    }, interval);
  });
});

io.listen(port);
console.log('listening on port ', port);

api.js

import io from 'socket.io-client';
const socket = io.connect('http://localhost:8000');

function subscribeToTimer(interval, cb) {
  socket.on('timer', timestamp => cb(null, timestamp));
  socket.emit('subscribeToTimer', 1000);
}
export { subscribeToTimer }

分量

class Root extends Component {
  constructor(props) {
    super(props);

    this.state = {
      timestamp: 'no timestamp yet'
    };
  }

  componentDidMount() {
    subscribeToTimer((err, timestamp) => this.setState({ timestamp }));
  }

  render() {
    return ( <p>{this.state.timestamp}</p> );
  }
}

每当我 运行 yarn start 并检查我的控制台时,时间间隔是 运行ning 正确,但是,它没有记录时间戳,而是重复显示 ERR_CONNECTION_REFUSED错误。

我在 运行本地 localhost:3000

使用 create-react-app 进行集成时是否需要额外的设置?

谢谢。

对于您的 server.js,您是否 运行 将其与 yarn run start 命令分开?如果不是,那将导致 ERR_CONNECTION_REFUSED.

当我 运行 单独处理时,我从您提供的代码中收到错误消息。事实证明您错过了 subscribeToTimer() 调用的时间间隔。将您的 componentDidMount 更改为

componentDidMount() {
  subscribeToTimer(100, (err, timestamp) => this.setState({ timestamp}));
}

应该可以解决问题。