我试图设置一个非常简单的应用程序以熟悉在 React 应用程序中使用 SOCKET.IO。服务器看起来像这样:
const io = require('socket.io')();
io.origins('*:*');
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);
});
});
const port = 8000;
io.listen(port);
console.log('listening on port ', port);
Run Code Online (Sandbox Code Playgroud)
使用 Create-React-App 设置的 React Client 如下所示:
import React, { Component } from 'react';
import './App.css';
import openSocket from 'socket.io-client';
const socket = openSocket('http://localhost:8000');
function subscribeToTimer(cb) {
socket.on('timer', timestamp => cb(timestamp));
socket.emit('subscribeToTimer', 1000);
}
class …Run Code Online (Sandbox Code Playgroud)