【node+小程序+web端】簡單的websocket通信

【node+小程序+web端】簡單的websocket通信

websoket是用來作什麼的?

聊天室 消息列表 拼多多
即時通信,推送, 實時交互html

websoket是什麼

websocket是一個全新的、獨立的協議,基於TCP協議,與HTTP協議兼容卻不會融入HTTP協議,僅僅做爲HTML5的一部分。vue

HTTP是個懶惰的協議,server只有收到請求才會作出迴應,不然什麼事都不幹。所以,爲了完全解決這個server主動像client發送數據的問題。W3C在HTML5中提供了一種client與server間進行全雙工通信的網絡技術WebSocket。node

node模塊websocket和socket.io的區別
websocket只是socket.io實現業務封裝的一個瀏覽器方面的backend,類比的話,websocket是tcp,而socket.io是http,後者當然基於前者,可是必需要找socket.io約定的protocol走git

用socket.io簡單的創建一個服務器

const http = require('http');
const io = require('socket.io');

// 建立http服務
let httpServer = http.createServer();
httpServer.listen(2333,()=>{
  console.log('on port 2333')
});
// 建立websocket服務,將socket.io綁定到服務器上
let wsServer = io.listen(httpServer,()=>{
  console.log('on port 2333')
});

wsServer.on('connection',function(sock){
  sock.on('a',function(num1,num2){
    console.log(`接到了瀏覽器發送的數據:${num1}`)
  })
  setInterval(function(){
    sock.emit('ttt',Math.random())
  },500)
})

用websocket搭建服務器github

const http = require('http')
const WebSocketServer = require('websocket').server

const httpServer = http.createServer((request, response) => {
    console.log('[' + new Date + '] Received request for ' + request.url)
    response.writeHead(404)
    response.end()
})

const wsServer = new WebSocketServer({
    httpServer,
    autoAcceptConnections: true
})

wsServer.on('connect', connection => {
    connection.on('message', message => {
        if (message.type === 'utf8') {
            console.log('>> message content from client: ' + message.utf8Data)
            connection.sendUTF('[from server] ' + message.utf8Data)
        }
    }).on('close', (reasonCode, description) => {
        console.log('[' + new Date() + '] Peer ' + connection.remoteAddress + ' disconnected.')
    })
})

httpServer.listen(8111, () => {
    console.log('[' + new Date() + '] Serveris listening on port 8080')
})

在html頁面調用websocketweb

<html>
  <body>
    <head>
      <script src="http://localhost:2333/socket.io/socket.io.js" charset="utf-8"></script>
      <script>
        let sock = io.connect('ws://localhost:2333')
        document.onclick=function(){
          sock.emit()
        }
        sock.on('ttt',function(n){
          console.log(`接到了服務器發送的${n}`)
        })
      </script>
    </head>
  </body>
</html>

在小程序端調用請求
小程序websocket-apinpm

localsession: function(data){
   wx.connectSocket({
     url: 'ws://localhost:8999'
   })
   wx.onSocketOpen(function (res) {
     console.log('WebSocket鏈接已打開!')
  setInterval(()=>{
  wx.sendSocketMessage({
    data: data,
  })
},3000)
   })

   wx.onSocketMessage(function (res) {
     console.log(res)
   })

   wx.onSocketClose(function (res) {
     console.log('WebSocket鏈接已關閉!')
   })
 },

WebSocket 與 Socket.IO小程序

在vue中運用websocketapi

  1. vue-websocket
  2. vue-socket.io
let ws = new WebSocket('ws://192.168.1.205:9032/websocket');
        ws.onopen = () => {
          // Web Socket 已鏈接上,使用 send() 方法發送數據
          //console.log('數據發送中...')
          //ws.send('Holle')
          //console.log('數據發送完成')
        }
        ws.onmessage = evt => {
          console.log('數據已接收...')
          var received_msg = evt.data;
          console.log(received_msg);

          if("notice" == received_msg)
          {
            this.initData();
            this.play();
          }
          else{
            console.log("不刷新");
          }
        }
       /* ws.onclose = function () {
          // 關閉 websocket
          console.log('鏈接已關閉...')
        }
        // 路由跳轉時結束websocket連接
        this.$router.afterEach(function () {
          ws.close()
        })*/
相關文章
相關標籤/搜索