function initWB (type,fn = () => {},auth = {username: 'ash', password: '123456'}) {
let ws = new WebSocket('ws://localhost:10086/test/'+type)
let isLogin = false
ws.onopen = (e) => {
ws.send(JSON.stringify(auth))
fn()
}
ws.onerror = (e) => {
console.log("error")
}
ws.onclose = (e) => {
console.log(type+" socket is closed")
}
ws.onmessage = (e) => {
if(!isLogin) {
isLogin = true
const data = JSON.parse(e.data)
if(+data.code !== 200){
console.log(data.message)
ws.close()
}
}else {
console.log(type+" recieve:"+e.data)
}
}
return ws
}
initWB("sub")
initWB("sub")
initWB("sub")
let add = initWB("add")
let test = initWB("add", () => {}, {password: 123456, username: 'adsf'})
let pub = initWB("pub", () => {
pub.send(JSON.stringify({eventType: 'add', message: 'send is ok'}))
pub.send(JSON.stringify({eventType: 'sub', message: 'send is ok'}))
})
console