微信小程序之监听局域网广播

// 微信小程序客户端
initUdpSocket() {
  this.setData({
    udpSocket: wx.createUDPSocket()
  })
  if (this.data.udpSocket === null) {
    console.log('暂不支持')
    return;
  }
  const locationPort = udpSocket.bind(8888)
  this.setData({
    'locationUrl.port': locationPort
  })
  udpSocket.onListening(function(res) {
    console.log('监听中...')
    console.log(res)
  })
  udpSocket.onMessage(function(res) {
    console.log(res)
    let unit8Arr = new Uint8Array(res.message.data);
    let encodedString = String.fromCharCode.apply(null, unit8Arr),
    decodedString = decodeURIComponent(escape((encodedString)));
    console.log(decodedString)
  })
}
// 服务端广播程序
package main

import (
    "log"
    "net"
    "time"

    socket "github.com/nulijiabei/socketgo"
)

func main() {
    // 开始
    for {
        // 建立UDP广播
        conn := socket.NewUDP("255.255.255.255", "8888", 3)
        // 读写
        err := conn.ReadWrite(func(conn *net.UDPConn) error {
            // 循环广播发送
            for {
                // 发送本机MAC
                _, err := conn.Write([]byte("www.nljb.net"))
                if err != nil {
                    return err
                }
                // 定时发送
                time.Sleep(time.Second * time.Duration(5))
            }
        })
        log.Println(err.Error())
    }
}