赞
踩
websocket.js中
//import e from “express”
//websocket的四个回调函数,onopen,onmessage,onerror,onclose
import { websocket } from "./Websocket" import {message} from 'antd' class createWebSocket { constructor(url){ this.connect(url) //console.log(url) this.myUrl = url //this.getMessage() } connect(url){//连接服务器 this.ws = new WebSocket(url) this.ws.onopen = (e) =>{ this.status = 'open' message.info('link succeed') console.log("connection to server is opened") //this.heartCheck.reset().start() this.ws.send('succeed') this.heartCheck() } } async getMessage (){//异步获取数据 this.lockReconnect = true this.messageList = ''; await new Promise((resolve) =>{ this.ws.onmessage = (e) =>{ //console.log(e.data) this.messageList = e.data //console.log(this.messageList) resolve() } }) console.log(this.messageList) return this.messageList } heartCheck () {//心跳 this.pingPong = 'ping' this.pingInterval = setInterval(() => { if(this.ws.readyState === 1){ this.ws.send('ping') } }, 10000); this.pongInterval = setInterval(()=>{ if(this.pingPong === 'ping'){ this.closeHandle('pingPong没有改为pong') } console.log('return the pong') },20000) } closeHandle(res){ if(this.status !== 'close'){ console.log('断开,重连websocket',res) if(this.pongInterval !== undefined && this.pingInterval !== undefined){ clearInterval(this.pongInterval) clearInterval(this.pingInterval) } this.connect(this.myUrl) }else{ console.log('websocket手动关闭了,或者正在连接') } } close(){//关闭连接 clearInterval(this.pingInterval) clearInterval(this.pongInterval) this.ws.send('close') this.status = 'close' this.ws.onclose = e =>{ console.log('close') } } } export default createWebSocket
在组件中使用,利用服务器端传来的值修改组件中state的值
import createWebSocket from '../WebSocket'
ws = new createWebSocket('ws:...')
componentDidMount(){
//this.test()
//console.log('xxxx')
this.ws.getMessage().then((res)=>{
console.log(res)
this.setState({data:res})
})
}
componentWillUnmount(){
this.ws.close()
}
利用node配一个本地服务器
server.js中
const WebSocket = require(‘ws’)
const express = require(‘express’)
const app = express()
app.listen(3003)
const wss = new WebSocket.Server({port:8989})
console.log(‘the connection is starting’)
wss.on(‘connection’,function(ws){
console.log(‘client connected’)
ws.on(‘message’,function(message){
console.log(‘received :’,message)
ws.send(‘hello world’)
})
})
在控制台node server.js启动这个服务器
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。