微信小程序开发WebSocket通讯

  • 官方文档说明:入口

  • WebSocket连接的链接只支持wss加密方式,且只能用域名的方式

  • 该域名还要在微信公众平台的小程序中登记才能使用,开发->开发管理->服务器域名->修改
    在这里插入图片描述

  • 该域名要和https使用的一致

  • 以域名地址:dtu.aabbcc.cn为例

nodejs搭建WebSocket服务器

无需传入服务器地址,底层会自动映射到公网ip

const WebSocket = require('ws');
const server = new WebSocket.Server({
    port: 3000 });
consoles.log('WebSocket服务器已启动');

// 当有客户端连接时,监听其消息
server.on('connection', (client) => {
   
  consoles.log('有客户端连接:', client._socket.remoteAddress);
  // 收到客户端消息
  client.on('message', (data) => {
   
    try {
   
      const decoder = new TextDecoder();
      const text = decoder.decode(data);
      message = JSON.parse(text);
      consoles.log('收到客户端消息:', message);
   
    } catch (error) {
   
      consoles.log('wss message error', error)
    }
  });
  // 当客户端断开连接时,从客户端映射关系中删除
  client.on('close', () => {
   
    consoles.log('客户端断开连接:', client._socket.remoteAddress);
    clientsInforList.delete(client);
  });
});

WebSocket默认是不带加密传输的,接下来可以通过代理服务器配置路由进行加密传输,即ws变成wss。

Apache配置参数

系统:ubuntu
配置文件:

  • 加密路由配置:\etc\apache2\sites-enabled\default-ssl.conf
	<VirtualHost _default_:443>
		ServerName wss://dtu.aabbcc.cn
		ProxyPass /wss ws://localhost:3000
		ProxyPassReverse /wss ws://localhost:3000
	</VirtualHost>
  • 不加密路由配置:\etc\apache2\sites-enabled\000-default.conf
<VirtualHost *:80>
	ServerName ws://dtu.aabbcc.cn
	ProxyPass /wss ws://localhost:3000
	ProxyPassReverse /wss ws://localhost:3000
</VirtualHost>

修改完记得重启Apache

sudo service apache2 restart

微信小程序端连接

      wx.connectSocket({
   
        url: 'wss://dtu.aabbcc.cn/wss',
        header:{
   
          'content-type': 'application/json',
          'Access-Control-Allow-Origin': '*',
        },
        success: function (res) {
   
          console.log('WebSocket连接成功', res)
        },
        fail: function (res) {
   
          console.log('WebSocket连接失败:', res)
        }
      })
      
      wx.onSocketOpen(function() {
   
        console.log('WebSocket连接已打开')
        wx.sendSocketMessage({
   
          data: JSON.stringify({
   
            type: 'register'
            ,id: 'wx-23423453'
          })
        })
      })
      wx.onSocketError(function(res) {
   
        console.log('WebSocket连接打开失败:', res)
      })
      wx.onSocketMessage(function(res) {
   
        console.log('WebSocket onSocketMessage:', res)
        var data = JSON.parse(res.data)
      })
      wx.onSocketClose(function() {
   
        console.log('WebSocket连接已关闭')
      })

相关推荐

  1. springboot+websocket+程序实现评论区功能

    2024-01-12 13:46:02       34 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-12 13:46:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-12 13:46:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-12 13:46:02       82 阅读
  4. Python语言-面向对象

    2024-01-12 13:46:02       91 阅读

热门阅读

  1. Unity-脚本

    2024-01-12 13:46:02       59 阅读
  2. 设计模式之避免共享的设计模式Copy-on-Write模式

    2024-01-12 13:46:02       68 阅读
  3. C语言程序由哪些部分组成?

    2024-01-12 13:46:02       61 阅读
  4. 如何编写项目交接文档

    2024-01-12 13:46:02       58 阅读
  5. [力扣 Hot100]Day3 最长连续序列

    2024-01-12 13:46:02       57 阅读
  6. 移动安全-certutil

    2024-01-12 13:46:02       51 阅读
  7. K8S---kubectl top

    2024-01-12 13:46:02       53 阅读
  8. 第28关 k8s监控实战之Prometheus(七)

    2024-01-12 13:46:02       61 阅读
  9. 【数据库】

    2024-01-12 13:46:02       52 阅读