微信小程序开发——websocket测试

服务端

在windows下执行 node  server.js

也可参照我的前一篇部署https

var httpServ = require(‘http‘)
var WebSocketServer = require(‘ws‘).Server;
var  app = httpServ.createServer().listen(8080);
var ws = new WebSocketServer({
    server: app
});

ws.on(‘connection‘, function(wsConnect) {
    wsConnect.on(‘message‘, function(message) {
        console.log(message);
        wsConnect.send(‘reply‘);
    });
    wsConnect.on(‘close‘, function (code, reason) {
        console.log(‘关闭连接‘, code, reason)
    });
    wsConnect.on(‘error‘, function (code, reason) {
        console.log(‘异常关闭‘, code, reason)
    });
})

客户端

这里介绍两种客户端,一种是微信小程序,一种是html网页。

微信小程序

代码示例:

xxx.wxml

<button bindtap=‘startClick‘>连接</button>
<button bindtap=‘sendClick‘>发送</button>
<button bindtap=‘closeClick‘>断开</button>

xxx.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isConnect: null,
  },

  startClick(even) {
    wx.connectSocket({
      url: ‘ws://localhost:8080/‘,
      method: ‘GET‘,
      success: (res) => {
        isConnect: true
        console.log("连接成功", res)
      },
      fail: (res) => {
        isConnect: false
        console.log("连接失败", res)
      }
    });

    wx.onSocketOpen((res) => {
      console.log(‘WebSocket连接已打开!‘)
    });

    wx.onSocketError((res) => {
      console.log(‘WebSocket连接打开失败,请检查!‘)
    })
  },

  sendClick: function (even) {
    wx.sendSocketMessage({
      data: "From微信小程序 web socket"
    })
  },

  closeClick(even) {
    wx.closeSocket({
      success: (res) => {
        console.log("关闭成功...")
      },
      fail: (res) => {
        console.log("关闭失败...")
      }
    });
    wx.onSocketClose((res)=>  {
      console.log("WebSocket连接已关闭")
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.onSocketMessage((res) => {
      console.log(res.data)
      console.log(res)
    })
  }
})

效果截图:

微信小程序开发——websocket测试

 

 网页

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>WebSocket</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body{
            width: 96%;
            margin-left: 2%;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<div class="btn-group box" role="group" aria-label="...">
    <button type="button" class="btn btn-default">Oppo</button>
    <button type="button" class="btn btn-default">Vivo</button>
    <button type="button" class="btn btn-default">Apple</button>
</div>
<div class="page-header">
    <h4 class="info">服务器返回信息列表:</br></br></h4>
</div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
    if (window.WebSocket) {
        var ws = new WebSocket(ws://127.0.0.1:8080);

        ws.onopen = function () {
            console.log(连接服务器成功!);
            ws.send(startting...);
        }
        ws.onclose = function () {
            console.log(服务器关闭);
        }
        ws.onerror = function () {
            console.log("连接出错");
        }

        ws.onmessage = function (e) {
            document.querySelector(".box").onclick = function (e) {
                ws.send(当前点击框的内容为:<font style="color:red;" > + e.target.innerHTML+</font>);
            }
            $(.info).append(e.data + </br></br>);
        }
    }
</script>
</body>
</html>

 

 

参考链接:

1. https://blog.csdn.net/potato512/article/details/79991342

2. https://blog.csdn.net/medivhq/article/details/75021382

 

微信小程序开发——websocket测试

上一篇:小程序连接后台上传图片


下一篇:商超行业微信小程序开发定制一般多少钱 (行业技术人员解读)