websocket 入门只需五分钟

导读:前后端实时通信常用的一种方式。
websocket 是一种采用socket 通信的连接,而不是http协议所以不受浏览器SOP的限制,是一种支持跨域访问的协议,客户端可以与任意服务器通信。

1、简单入门

1.1 初始化websocket

   initWebsockt() {
      if (typeof WebSocket === 'undefined') {
        console.log('您的浏览器不支持WebSocket')
        return
      } else {
        // 建立连接
        this.websocket = new WebSocket(this.url)
        // 连接成功
        this.websocket.onopen = this.onOpen
        // 客户端接收服务端返回的数据
        this.websocket.onmessage = this.onMessage
        // 发生错误时
        this.websocket.onerror = this.onError
        // 关闭连接时
        this.websocket.onclose = this.onClose
      }
    },

1.2 定义事件处理函数

    // 连接成功事件
    onOpen() { },
    
    // 接收数据
    onMessage(data) {
      console.log(JSON.parse(data))
      // todo 处理数据
    },

    // 连接出错事件
    onError() {
    

你可能感兴趣的:(websocket,网络协议,网络)