我正在将express.server与socket.io配合使用,并响应应用程序。代码正常工作,并且按预期方式发送/接收数据,但我一直注意到控制台中的连接错误:
与'ws://192.168.1.102:3000 / sockjs-node / 351 / m2x50td4 / websocket'的WebSocket连接失败:在建立连接之前已关闭WebSocket。
与'ws:/socket.io/?EIO = 3&transport = websocket'的WebSocket连接失败:WebSocket在建立连接之前已关闭。
websocket.js:118到'ws://192.168.1.102:3000 / socket.io /?EIO = 3&transport = websocket&sid = fNkATGvOmjkq9po1AAAE'的WebSocket连接失败:连接已关闭,但未收到握手响应
Express Server
const express = require('express');
const port = 5000;
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server, {'transports': ['websocket', 'polling']});
// WebSocket handlers
io.on('connection', (client) => {
console.log('Websocket: New connection from'+ client.request.connection.remoteAddress);
client.on('setSwitchState', function (data, fn) {
switchController.setSwitch(data);
fn(data['jstate']);
});
client.on('disconnect', () => {
console.log('user disconnected');
})
});
server.listen(port, () => console.log(`Listening on port ${port}`));
反应应用
import React, { Component } from "react";
import io from 'socket.io-client';
const socket = io();
class ToggleSwitch extends Component {
socket.emit('setSwitchState', sendata, (data) => {
this.setState({checked: data});
});
}
}
export default (ToggleSwitch);