• 【node+小程序+web端】简单的websocket通讯


    【node+小程序+web端】简单的websocket通讯

    websoket是用来做什么的?

    聊天室 消息列表 拼多多
    即时通讯,推送, 实时交互

    websoket是什么

    websocket是一个全新的、独立的协议,基于TCP协议,与HTTP协议兼容却不会融入HTTP协议,仅仅作为HTML5的一部分。

    HTTP是个懒惰的协议,server只有收到请求才会做出回应,否则什么事都不干。因此,为了彻底解决这个server主动像client发送数据的问题。W3C在HTML5中提供了一种client与server间进行全双工通讯的网络技术WebSocket。

    node模块websocket和socket.io的区别
    websocket只是socket.io实现业务封装的一个浏览器方面的backend,类比的话,websocket是tcp,而socket.io是http,后者固然基于前者,但是必须要找socket.io约定的protocol走

    用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搭建服务器

    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页面调用websocket

    <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-api

     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中运用websocket
    1.
    vue-websocket
    2.
    vue-socket.io
    3.

     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()
            })*/
    
  • 相关阅读:
    自定义类型转换器之TypeConverter
    python测试工具nosetests
    算法练习之相同的树,对称二叉树
    算法练习之x的平方根,爬楼梯,删除排序链表中的重复元素, 合并两个有序数组
    算法练习之报数, 最大子序和,最后一个单词的长度,加一,二进制求和
    java.sql.SQLException: Zero date value prohibited
    java打包小记
    修改jar的.class文件,并重新打包
    算法练习之合并两个有序链表, 删除排序数组中的重复项,移除元素,实现strStr(),搜索插入位置,无重复字符的最长子串
    解决GitHub访问速度慢的问题
  • 原文地址:https://www.cnblogs.com/teemor/p/9636334.html
Copyright © 2020-2023  润新知