微信小程序使用TCP通信

最终目的:在微信小程序内实现对局域网发起TCP通信

实现步骤:建立TCP服务 + 小程序发起通信

建立TCP服务

第一步:引入net模块(http模块是基于net模块之上的)

const net = require('net');

第二步:新建TCP服务,同时进行各种生命周期事件的监听

const server = net.createServer((socket) => {
  console.log('接收到了tcp请求');

  // 发送数据到客户端
  socket.write('服务器tcp连接成功,接下来每三秒会推送消息给你', 'utf8');

  // 每隔三秒发送一次数据进行测试
  let timer = null
  let i = 1
  timer = setInterval(() => {
    socket.write(`tcp推送的第${i++}条消息`);
  }, 3000)


  // 关闭链接时清除定时器
  server.on('close', () => {
    timer && clearInterval(timer)
    i = 0
    console.log('关闭tcp链接');
  });

 // 监听客户端服务发送
  server.on('data', (data) => {
    console.log('接收到了数据,数据为 ' + data);
  });

  server.on('error', (err) => {
    console.error('失败: ' + err);
  });

});

第三步:开启TCP服务

server.listen(1400, '192.168.7.102', () => {
  console.log('开始监听');
  // 在这里可以发送和接收数据
});

小程序发起通信

<template>
  <view>
    <button @click="getWifiInfo">获取正在连接的wifi信息</button>
    局域网ip
    <input type="text" v-model="ip" />
    局域网端口
    <input type="text" v-model="port" />

    <button @click="connect">建立tcp链接</button>

    <!-- 打印信息 -->
    <view v-for="(item, index) in infoList" :key="index">
      {{ item }}
    </view>
  </view>
</template>

<script>
  // ArrayBuffer转string
  const transitionArrayBufferToString = arrayBuffer => {
    // 将 ArrayBuffer 转换为 Uint8Array
    const uint8Array = new Uint8Array(arrayBuffer)

    // 创建一个存放字符的数组
    const characters = []

    // 遍历 Uint8Array 并将每个字节转换为字符
    for (let i = 0; i < uint8Array.length; i++) {
      characters.push(String.fromCharCode(uint8Array[i]))
    }

    // 使用数组的 join 方法将字符连接成字符串,并指定字符编码为 UTF-8
    const text = decodeURIComponent(escape(characters.join('')))

    return text
  }

  export default {
    data() {
      return {
        data: '拉',
        tcp: '',
        infoList: [],
        ip: '192.168.7.102',
        port: '1400',
        message: '',
      }
    },
    onLoad() {
      this.wifiInit()
    },
    methods: {
      // 初始化wifi模块
      wifiInit() {
        wx.startWifi({
          fail(error) {
            console.log('初始化wifi-失败', error)
          },
          success(res) {
            console.log('初始化wifi-成功', res)
          },
        })
      },
      // 获取wifi信息
      getWifiInfo() {
        wx.getConnectedWifi({
          partialInfo: true,
          fail(error) {
            console.log('获取失败', error)
          },
          success(res) {
            console.log('wifi信息', res)
          },
        })
      },
      // tcp链接
      connect() {
        // 初始化TCP实例
        this.tcp = wx.createTCPSocket()
        // tcp实例向服务端发起连接
        this.tcp.connect({ address: this.ip, port: ~~this.port })
        this.infoList.push(`向${this.ip}:${~~this.port}建立链接`)

        this.tcp.onClose(() => {
          this.infoList.push('关闭')
          this.tcp.close()
        })
        this.tcp.offClose(() => {
          this.infoList.push('offClose')
        })
        this.tcp.onConnect(() => {
          this.infoList.push('连接成功')
        })
        this.tcp.offConnect(() => {
          this.infoList.push('offConnect')
        })
        this.tcp.onError(error => {
          this.infoList.push('异常:' + error)
        })
        this.tcp.onMessage(data => {
          // data是一个对象,服务端发送的数据在message属性里,且message微信这边得到的是一个ArrayBuffer格式的数据,所以需要转换一下
          this.infoList.push('接收到数据: ' + transitionArrayBufferToString(data.message))
        })
      },
    },
  }
</script>

注意:

  1. 微信小程序的TCP只能访问局域网以及通过备案且在小程序后台配置好的公网
  2. 小程序示例代码中的wifi部分是为了查看用户连接的wifi是否有问题,可按需删除
微信小程序不能直接进行 TCP 通信,但可以通过 WebSocket 协议实现双向通信。WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,它首先使用 HTTP 协议发起一次特殊的握手请求,然后在握手成功后,双方可以随时发送和接收消息。 具体实现步骤如下: 1. 在服务器端启用 WebSocket,监听客户端连接请求。 2. 在微信小程序中调用 wx.connectSocket() 方法连接服务器。 3. 监听连接打开、连接关闭、收到消息等事件,分别对应 onOpen、onClose、onMessage 方法,可以在方法中进行相关操作。 4. 发送消息可以使用 wx.sendSocketMessage() 方法,接收消息则可以在 onMessage 方法中获取。 需要注意的是,在微信小程序使用 WebSocket 时,需要在小程序后台设置域名白名单,且只支持 wss:// 开头的安全连接。另外,需要在小程序的 app.json 文件中声明 socket 相关权限,例如: ```json "permission": { "scope.userLocation": { "desc": "你的位置信息将用于小程序位置接口的效果展示" }, "scope.record": { "desc": "你的录音功能将用于小程序语音识别效果展示" }, "scope.writePhotosAlbum": { "desc": "你的相册将用于小程序保存图片" }, "scope.camera": { "desc": "你的相机将用于小程序拍照" }, "scope.userInfo": { "desc": "获取用户信息" }, "scope.userLocationBackground": { "desc": "小程序后台定位" }, "scope.werun": { "desc": "微信运动步数" }, "scope.writeVideoToPhotosAlbum": { "desc": "保存视频到相册" }, "scope.socket": { "desc": "使用 WebSocket" } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

易风920

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值