套接字连接有什么问题? [英] Whats the problem with the socketio connection?
问题描述
当我接收数据或将数据发送到套接字连接时,在控制台中,我会在1-3分钟内收到很多http请求( 6k INSIDE LAGGING ).
Im having this alot of http petitions (6k INSIDE LAGGING) in 1-3 minutes in the console when i receive or send data to a socketio connection.
我在后端使用node + express,在前端使用vue
后端:
app.js
mongoose.connect('mongodb://localhost/app',{useNewUrlParser:true,useFindAndModify:false})
.then(result =>{
const server = app.listen(3000)
const io = require('./sockets/socket').init(server)
io.on('connection', socket =>{
// console.log('client connected')
})
if(result){console.log('express & mongo running');
}
})
.catch(error => console.log(error))
我创建了一个io实例以在路由上使用它
let io
module.exports = {
init: httpServer => {
io = require('socket.io')(httpServer)
return io;
},
getIo:()=>{
if(!io){
throw new Error('socket io not initialized')
}
return io;
}
}
然后,在路由上,根据逻辑,如果是,则选择套接字响应的类型
router.post('/post/voteup',checkAuthentication, async (req,res)=>{
//some logic
if(a.length <= 0){
io.getIo().emit('xxx', {action:'cleanAll'})
}
else if(b.length <= 0){
io.getIo().emit('xxx', {action:'cleanT',datoOne})
}
else{
io.getIo().emit('xxx', {action:'cleanX',dataTwo,dataOne,selected})
}
res.json({ serverResponse:'success'})
})
在前面(组件)(已使用beforeUpdate生命周期挂钩激活)
getData(){
let socket = openSocket('http://localhost:3000')
socket.on('xxx', data => {
if(data.action === 'cleanX'){
if(this.selected === data.selected){
this.ddd = data.dataTwo
}
else if(!this.userTeamNickname){
this.qqq= data.dataOne
}
}
else if(data.action === 'cleanAll'){
this.ddd= []
this.qqq= []
}
else if(data.action === 'cleanT'){
this.ddd= data.dataOne
}
})
},
1.什么样的行为会产生这种错误?2.还有其他最有效的方法吗?
推荐答案
socket.io似乎无法建立webSocket连接,并且从未进行过轮询.默认情况下,socket.io连接从http轮询开始,经过与服务器的协商后,它尝试建立webSocket连接.如果成功,它将停止进行轮询并仅使用webSocket连接.如果webSocket连接失败,它将继续进行轮询.
It looks like socket.io is failing to establish a webSocket connection and has never advanced out of polling. By default, a socket.io connection starts with http polling and after a bit of negotiation with the server, it attempts to establish a webSocket connection. If that succeeds, it stops doing the polling and uses only the webSocket connection. If the the webSocket connection fails, it just keeps doing the polling.
以下是可能发生的一些原因:
Here are some reasons that can happen:
- 客户端和服务器中的socket.io版本不匹配.
- 客户端和服务器之间有一些基础结构(代理,防火墙,负载平衡器等),这些基础结构不允许webSocket连接通过.
- 您已将多个socket.io服务器处理程序附加到同一Web服务器.您无法执行此操作,因为当多个服务器处理程序尝试响应同一客户端时,通信将变得非常混乱.
作为测试,您可以强制客户端仅与webSocket连接(根本不启动轮询),然后查看连接是否失败:
As a test, you could force the client to connect only with webSocket (no polling at all to start) and see if the connection fails:
let socket = io(yourURL, {transports: ["websocket"]})'
socket.on('connect', () => {console.log("connected"});
socket.on('connect_error', (e) => {console.log("connect error: ", e});
socket.on('connect_timeout', (e) => {console.log("connect timeout: ", e});
这篇关于套接字连接有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!