websocket 笔记

320 阅读1分钟

=================== websocket ====================

概念

  • websocket是一种通信协议,建立在tcp之上。
  • 常用在 server <--> client 互相推送消息场景。
  • http兼容, 握手采用http 协议。
  • 可以发送文本 & 二进制数据
  • 没有同源策略限制

格式

  • ws://xxx.com:3000/path
  • wss://xxx.com:3000/path

client 端 WebSocket 对象:

	init() {
      this.ws = new WebSocket('ws://localhost:3000/websocket/'+ 1)
      this.ws.onopen = function (evt) {
          console.log('open ',evt);  
      }
      this.ws.onclose = function (evt) {
          console.log('onclose ',evt);  
          this.ws = null
      }
      this.ws.onmessage = function (evt) {
          console.log('onmessage ',evt);  
      }
    },
    close() {
      if(this.ws) {
        this.ws.close()
      }
    },
    send() {
      this.ws.send('hello ws jjm~~~~~~~~~~')
    }

server 端 websocket 实现:

  • koa-websocket
  • socket.io
const Koa = require('koa')
const Router = require('koa-router')
const websockify = require('koa-websocket')

const app = websockify(new Koa())
const router = new Router()

app.ws.use((ctx, next) => {
  return next(ctx)
})

router.get('/', async ctx => {
  ctx.body = '欢迎'
})

router.all('/websocket/:id', async ctx => {
  let t = setInterval(function() {
    let n = Math.random()
    if(n > 0.3) {
      let msg = JSON.stringify({ 'id': ctx.params.id, 'n': n })
      ctx.websocket.send(msg)
    }
  }, 1000)
  ctx.websocket.on('message', msg => {
    console.log('前端发过来的数据:', msg)
  })
  ctx.websocket.on('close', () => {
    console.log('前端关闭了websocket')
  })
})

app
.ws
.use(router.routes())
.use(router.allowedMethods())

app.listen(3000, () => {
  console.log('koa is listening in 3000')
})