websoket的扫码登陆简单用法
1 import { parseString } from 'xml2js'; // json与xml相互转化的工具 2 export default class ConnnectIm { 3 constructor() { 4 const ip = process.env.imUri; 5 const host = "ws://" + ip + ":7070/ws/"; 6 const connection = new WebSocket(host, 'xmpp') 7 this.connection = connection 8 this.ip = ip 9 this.id = null 10 let firstIn = true 11 connection.onopen = () => { //建立连接 12 connection.send(`<open to='${ip}' xmlns='urn:ietf:params:xml:ns:xmpp-framing' xml:lang='zh' version='1.0'/>`) 13 14 connection.send(`<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'>=</auth>`) 15 connection.onmessage = (res) => { //接受数据 16 parseString(res.data, (err, json) => { 17 if (json.open) { 18 this.id = json.open.$.id; 19 connection.send(`<iq type='set' id='${json.open.$.id}'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/></iq>`) 20 } 21 if (json.iq) { 22 connection.send(`<presence id="${this.id}"><status>Online</status><priority>1</priority></presence>`) 23 if(json.iq.bind[0].jid){ 24 this.sendJid && this.sendJid(json.iq.bind[0].jid[0]) 25 } 26 27 } 28 if (json.message && json.message.body) { 29 const body = JSON.parse(json.message.body[0]) 30 switch (body.ext && body.ext.type) { 31 case "userCenterinfo": 32 this.receive && this.receive(body); 33 break; 34 default: 35 return 36 } 37 } 38 }) 39 } 40 connection.onclose = ()=>{ 41 // 关闭 websocket 42 console.log("连接已关闭..."); 43 }; 44 } 45 } 46 47 on(action, event) { 48 this[action] = event.bind(this) 49 } 50 51 52 }
getQR(){ // 创建img标签将接受后端的二进制流转化为url const imconnect = new ImConnet(); this.setState({ imconnect }) let that = this; const { imgNode } = this.state; //document.createElement('img') imconnect.on('sendJid',function(e){ Ajax.get('getQr',{imJid: e}, (res)=>{ const myBlob = new window.Blob([res], {type: 'image/jpeg'}) const qrUrl = window.URL.createObjectURL(myBlob); // 生成的带有当前域名的标准blob:链接形式(blob:http://authorization.hqjy.com/4dc453be-bd07-4351-8484-6469f6112b23) imgNode.src = qrUrl; imgNode.onload = ()=> { window.URL.revokeObjectURL(qrUrl); // 当图片加载完成后释放对象URL. } that.qrImgBox.appendChild(imgNode); // 将img插入到div容器中 }) }) imconnect.on('receive',function(e){ console.log(e,'receive') const token = e.content; that.setState({ isOverDue: false, isSweeped: true })
// 超过十分钟断开连接,记得释放内存 setTimeout(()=>{ imconnect.connection.close(); this.setState({ isOverDue: true, isSweeped: false }) },1000*60*10)
参考链接
https://www.cnblogs.com/liulangmao/p/4262565.html