少年不搬砖老大徒伤悲

少年不搬砖老大徒伤悲

首先,微信用户打开小程序,需要自动登陆,检查session,如果过期,则重登录

 wx.checkSession({
        success: function (res) {
        },
        fail: function (res) {
          console.log("需要重新登录");
          wx.login({
            success(res) {
              if (res.code) {
                console.log("用户登陆凭证" + res.code);
                wx.request({
                  url: 'http://localhost:62923/index.aspx',
                  data: {
                    code: res.code,
                  },
                  success(res) {
                    console.log("获取openid: " + res.data.openid + "  session_key: " + res.data.session_key);
                  }
                })
              }
            }


          });

        }
      });

Login 获得 code 从后台换取 openid(用户唯一标识) 和session key(解码加密信息)

 string js_code = Request.QueryString["code"];
        string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=wxd4137ad6add09a40&secret=c147d93a4a810d42e0b4bde3a0d3fb51&js_code=" + js_code + "&grant_type=authorization_code";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
        request.Method = "GET";
        request.ContentType = "text/html;charset=UTF-8";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
        string retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();
        Response.Write(retString);

加载用户信息(改版)现在换成用 数据组件或者button

//wx.getUserInfo({

// data: { withCredentials: true },

// success(res) {

// console.log(res.userInfo.nickName + "/");

// }

// });

然后,配置Socket 服务-HPSocket=>httpSever 创建websocket

(1)HP socket 需要HPSocket4C_U.dll和 HPSocketCS.DLL 必须是32位,64位无用

(2) 小程序 连接 不能放在app.js 里,否则连不上,握手一直卡住。

const app = getApp();
const config = app.config;
const wafer = require('../../vendors/wafer-client-sdk/index');
const lab = require('../../lib/lab');

Page({
  data: {
    status: 'waiting',
    url: 'wss://' + config.host + '/ws',
    connecting: false,
    hintLine1: '完成服务器开发,',
    hintLine2: '让服务器支持 WebSocket 连接'
  },

  /**
   * WebSocket 是否已经连接
   */
  socketOpen: false,

  /**
   * 开始连接 WebSocket
   */
  connect() {
    this.setData({
      status: 'waiting',
      connecting: true,
      hintLine1: '正在连接',
      hintLine2: '...'
    });
    this.listen();
    wafer.setLoginUrl(`https://${config.host}/login`);
    wafer.login({
      success: () => {
        const header = wafer.buildSessionHeader();
        const query = Object.keys(header).map(key => `${key}=${encodeURIComponent(header[key])}`).join('&');
        wx.connectSocket({
          // 小程序 wx.connectSocket() API header 参数无效,把会话信息附加在 URL 上
          url: `${this.data.url}?${query}`,
          header
        });
      },
      fail: (err) => {
        this.setData({
          status: 'warn',
          connecting: false,
          hintLine1: '登录失败',
          hintLine2: err.message || err
        });
      }
    });
  },

  /**
   * 监听 WebSocket 事件
   */
  listen() {
    wx.onSocketOpen(() => {
      this.socketOpen = true;
      this.setData({
        status: 'success',
        connecting: false,
        hintLine1: '连接成功',
        hintLine2: '现在可以通过 WebSocket 发送接收消息了'
      });
      console.info('WebSocket 已连接');
    });
    wx.onSocketMessage((message) => {
      this.setData({
        hintLine2: message.data
      });
      lab.finish('websocket');
    });
    wx.onSocketClose(() => {
      this.setData({
        status: 'waiting',
        hintLine1: 'WebSocket 已关闭'
      });
      console.info('WebSocket 已关闭');
    });
    wx.onSocketError(() => {
      setTimeout(() => {
        this.setData({
          status: 'warn',
          connecting: false,
          hintLine1: '发生错误',
          hintLine2: 'WebSocket 连接建立失败'
        });
      });
      console.error('WebSocket 错误');
    });
  },

  /**
   * 发送一个包含当前时间信息的消息
   */
  send() {
    wx.sendSocketMessage({
      data: new Date().toTimeString().split(' ').shift() + '.' + (new Date().getMilliseconds())
    });
  },

  /**
   * 关闭 WebSocket 连接
   */
  close() {
    this.socketOpen = false;
    wx.closeSocket();
  }
});

下一步, 又是反向代理,因为必须使用wss合法域名访问,要转发到 ws 上去。

05-01 19:33