问题描述
对不起,我英语不好。
我尝试使用http令牌身份验证与socket.io作为交换数据连接到服务器。当socket.io出现错误时,请通过http请求令牌,然后尝试重新连接。
我将连接函数放在类中,然后从主程序中调用它。我的问题是,当我创建多个客户端时,为什么只能持续工作,这里是我的代码
呼叫课程
const SocketHttpClient = require('./class/socket-http-client')
let ioClient_1 = new SocketHttpClient('localhost',3001,'admin','/login')
let ioClient_2 = new SocketHttpClient('localhost',3002,'/login')
let ioClient_3 = new SocketHttpClient('localhost',3003,'/login')
连接类别
// =================================================================================================
// INCLUDE LIBRARY
// =================================================================================================
const ioClient = require('socket.io-client')
const http = require('http')
const cookie = require('cookie')
const log = require('./log-custom')
// =================================================================================================
// VARIABLE
// =================================================================================================
let data
let httpOption
ioOption = {
transportOptions: {
polling: {
extraHeaders: {
Cookie: 'hello=world'
}
}
}
}
module.exports = class Socket {
constructor(ioHostname,ioPort,httpUsername,httpPassword,loginPath) {
data = {
username: httpUsername,password: httpPassword
}
data = JSON.stringify(data)
httpOption = {
hostname: ioHostname,port: ioPort,path: loginPath,method: 'POST',headers: {
'Content-Type': 'application/json','Content-Length': data.length
}
}
log(`Connecting to "${httpOption.hostname}:${httpOption.port}"`)
this.io = ioClient(`http://${httpOption.hostname}:${httpOption.port}`,ioOption)
this.io.on('connect',() => {
log(`Connected to socket "${httpOption.hostname}:${httpOption.port}"`)
})
this.io.on('disconnect',() => {
log(`disconnected to socket "${httpOption.hostname}:${httpOption.port}"`)
log('Reconnecting...')
})
this.io.on('error',() => {
console.log(`error: ${httpOption.hostname}:${httpOption.port}`)
// When error then try to reconnect...
setTimeout(() => {
this.io.disconnect()
this.io.close()
this.req = http.request(httpOption,res => {
this.c = cookie.parse(res.headers['set-cookie'][0])
ioOption.transportOptions.polling.extraHeaders.Cookie = `sid=${this.c.sid}`
this.io.io.opts.query = ioOption
})
this.req.write(data)
this.req.end()
this.req.on('error',err => {
})
// delay to reconnect
setTimeout(() => {
this.io.connect()
},1000)
},1000)
})
}
}
结果:
ioClient_1 =>无法正常工作
ioClient_2 =>无法正常工作
ioClient_3 =>正常运行
我在哪里做错了?需要你们的建议。谢谢你。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)