使用基本的快速设置,我无法到达io.on('connect ')回调。连接刚刚停止
节点12.14.1快捷方式4.17.1socket.io3.0.1
代码
import express, { ErrorRequestHandler } from 'express';
import path from 'path';
import {Server} from 'socket.io';
import http from 'http';
import cors from 'cors';
import createError from 'http-errors';
import defaultRouter from './routes';
const app = express();
app.use(cors({origin:'*'}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname ,'../public')))
app.get("/",(req,res)=>{return res.sendFile(path.join(__dirname,'public','index.html')) })
app.use(defaultRouter);
app.use((req, res, next) => {
const { url } = req;
const message = `Page not found ${url}`;
next(new createError.NotFound(message));
});
const DefaultErrorHandler: ErrorRequestHandler = (err, req, res, next) => {
if (err && err.statusCode) {
return res.status(err.statusCode).send(err);
}
res.status(500).send('Yeah...my bad');
};
app.use(DefaultErrorHandler);
app.listen(3000, () => {
console.log('App listening on port 3000');
});
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', function (socket:any) {
console.log("connected")
io.emit("user connected")
socket.on('disconnect',()=>{console.log('disconnected')})
});
io.use((socket:any, next: any)=>{console.log(socket.request); next()})
server.listen(3001 )
server.on("listening",()=>{console.log('ws listening on 3001')} )
server.on("error",()=>{console.log('error')} )
WebSocket调用
$ websocat ws://localhost:3001/socket.io/?EIO=3\&transport=websocket
>0{"sid":"Q9Jj3CNtm6MSarmEAAAA","upgrades":[],"pingInterval":25000,"pingTimeout":5000}
>2
除错
engine handshaking client "Q9Jj3CNtm6MSarmEAAAA" +0ms
engine:socket sending packet "open" ({"sid":"Q9Jj3CNtm6MSarmEAAAA","upgrades":[],"pingInterval":25000,"pingTimeout":5000}) +0ms
engine:socket flushing buffer to transport +0ms
engine:ws writing "0{"sid":"Q9Jj3CNtm6MSarmEAAAA","upgrades":[],"pingInterval":25000,"pingTimeout":5000}" +0ms
engine:transport setting request +0ms
socket.io:server incoming connection with id Q9Jj3CNtm6MSarmEAAAA +4s
engine:socket writing ping packet - expecting pong within 5000ms +25s
engine:socket sending packet "ping" (undefined) +1ms
engine:socket flushing buffer to transport +0ms
engine:ws writing "2" +25s
engine:ws closing +5s
socket.io:client client close with reason ping timeout +0ms
socket.io:client no namespace joined yet, close the client +15s
当使用firecamp时,它会连续连接和断开连接,并且不会使用轮询传输进行连接
我不知道发生了什么与这些连接,我打破了它尽可能简单,并得到了相同的结果,侧记,我没有得到pong通知消防营。我打破了它,以最小的,从来没有达到“连接”块
2条答案
按热度按时间watbbzwu1#
我知道评论中提到了这一点,但很难找到,这是一个被严重低估的答案:
确保www.example.com的客户端和服务器版本socket.io一致(仅获取两者的最新版本以确保一致)。
有一段时间,我一直在为连接问题而挣扎,这是因为我正在使用的另一个库已经安装了一个较低版本的socket.io服务器供自己使用。
我自己甚至从未socket.io在服务器上安装过www.example.com,但当我导入它时,导入工作正常,因为它找到了由该库安装的socket.io。
我只需要运行
npm install --save socket.io
,我的连接问题就消失了。liwlm1x92#
您的配置有问题。请按照下面经过完美测试的代码操作。
这是为了在同一个端口创建一个服务器和套接字,根据需要添加其他代码。