react中使用封装websocket

月大侠 2020-09-16 08:23:48
websocket.js中
import { websocket } from "./Websocket"
import {message} from 'antd'
//import e from "express"

//websocket的四个回调函数,onopen,onmessage,onerror,onclose

class createWebSocket {
//myUrl = ''
constructor(url){

//this.instance = null
//super(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启动这个服务器
...全文
5622 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
hookee 2020-09-22
  • 打赏
  • 举报
回复
yinxu 2020-09-21
  • 打赏
  • 举报
回复
有socket.io和socket.io-client啊

87,921

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧