[教程]微信小程序之websocket开发系列(一)
2016-9-27
原创作者:direction

1.准备工作

l  Centos 6.5建立的Wesocket服务器:

这里使用的是PHP7.1 +Swoole作为websocket服务器

l  破解了的微信开发工具

l  微信小程序文档


2.Websocket搭建

  2.1.Linux环境下安装

Linux操作系统通常都有自己的包管理软件(Ubuntuapt-getCentOSyumMac OSXHomeBrew等),因此一般情况下可以通过这些包管理软件直接安装PHP。但是这样安装的PHP不太适用于运行Swoole,因此本章将介绍如何通过源码编译安装。

编译环境

想要编译安装PHP首先需要安装对应的编译工具。 Ubuntu上使用如下命令安装编译工具和依赖包:

sudo apt-get install \
build-essential \
gcc \
g++ \
autoconf \
libiconv-hook-dev \
libmcrypt-dev \
libxml2-devel \
libmysqlclient-dev \
libcurl4-openssl-dev \
libjpeg8-dev \
libpng12-dev \
libfreetype6-dev \

PHP安装

PHP下载地址 在这里挑选你想用的版本即可。下载源码包后,解压至本地任意目录(保证读写权限)。

使用如下命令编译安装PHP

cd php-5.6.22/
./configure --prefix=/usr/local/php \
--with-config-file-path=/etc/php \
--enable-fpm \
--enable-pcntl \
--enable-mysqlnd \
--enable-opcache \
--enable-sockets \
--enable-sysvmsg \
--enable-sysvsem \
--enable-sysvshm \
--enable-shmop \
--enable-zip \
--enable-soap \
--enable-xml \
--enable-mbstring \
--disable-rpath \
--disable-debug \
--disable-fileinfo \
--with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--with-pcre-regex \
--with-iconv \
--with-zlib \
--with-mcrypt \
--with-gd \
--with-openssl \
--with-mhash \
--with-xmlrpc \
--with-curl \
--with-imap-ssl

sudo make
sudo make install
sudo mkdir /etc/php
sudo cp php.ini-development /etc/php/php.ini

注意,以上PHP编译选项根据实际情况可调整。

另外,还需要将PHP的可执行目录添加到环境变量中。 使用Vim/Sublime打开~/.bashrc,在末尾添加如下内容:

export PATH=/usr/local/php/bin:$PATHexport PATH=/usr/local/php/sbin:$PATH

保存后,终端输入命令:

source~/.bashrc

此时即可通过php --version查看php版本。


2.2.Mac环境下安装

Mac系统自带PHP,但是Mac上对于OpenSSL的相关功能做了一些限制,使用了一个Secure Transport来取代OpenSSL。因此仍然建议重新编译安装PHP环境。


安装OpenSSL

Mac原装的0.9.8版本的OpenSSL使用的时候会有些Warning,反正我看不惯……

安装命令:

brew install openssl

安装之后,还需要链接新的openssl到环境变量中。

brew link --force openssl

安装Curl

Mac系统原装的Curl默认使用了Secure Transport,导致通过option函数设置的证书全部无效。果断重新安装之。

brew install curl --with-openssl && brew link curl --force

安装PHP

PHP官网上下载某个版本的PHP(我选择的是5.6.22),使用如下命令编译安装。

cd /path/to/php/
./configure
--prefix=/usr/local/php
--with-config-file-path=/etc/php
--with-openssl=/usr/local/Cellar/openssl/1.0.2g/
--with-curl=/usr/local/Cellar/curl/7.48.0/

make && make install

这里我仅列出两个需要特殊设置的选项with-opensslwith-curl 安装完成后,执行如下命令:

sudo cp /usr/local/php/bin/php /usr/bin/
sudo cp /usr/local/php/bin/phar* /usr/bin/
sudo cp /usr/local/php/bin/php-config /usr/bin/
sudo cp /usr/local/php/bin/phpize /usr/bin/

随后,设置php.ini

sudo mkdir /etc/php
sudo cp php.ini.development /etc/php/php.ini

2.3.Swoole扩展安装

Swoole扩展下载地址 解压源码至任意目录,执行如下命令:

cd swoole-src-swoole-1.7.6-stable/
phpize
./configure
sudo make
sudo make install

swoole./configure有很多额外参数,可以通过./configure --help命令查看,这里均选择默认项)

安装完成后,进入/etc/php目录下,打开php.ini文件,在其中加上如下一句:

extension=swoole.so

随后在终端中输入命令php -m查看扩展安装情况。如果在列出的扩展中看到了swoole,则说明安装成功。


2.4.可能出现的问题

CentOS编译PHP5的时候有时会遇到以下的一些错误信息,基本上都可以通过yum安装相应的库来解决。以下是具体的一些解决办法:


checking for BZip2 support… yes checking for BZip2 in default path… not found configure: error: Please reinstall the BZip2 distribution

Fix: yum install bzip2-devel


checking for cURL support… yes checking if we should use cURL for url streams… no checking for cURL in default path… not found configure: error: Please reinstall the libcurl distribution – easy.h should be in/include/curl/

Fix: yum install curl-devel

 

checking for curl_multi_strerror in -lcurl… yes checking for QDBM support… no checking for GDBM support… no checking for NDBM support… no configure: error: DBA: Could not find necessary header file(s).

Fix: yum install db4-devel


checking for fabsf… yes checking for floorf… yes configure: error: jpeglib.h not found.

Fix: yum install libjpeg-devel


checking for fabsf… yes checking for floorf… yes checking for jpeg_read_header in -ljpeg… yes configure: error: png.h not found.

Fix: yum install libpng-devel


checking for png_write_image in -lpng… yes If configure fails try –with-xpm-dir=

configure: error: freetype.h not found.

Fix: Reconfigure your PHP with the following option. --with-xpm-dir=/usr yum install freetype-devel


checking for png_write_image in -lpng… yes configure: error: libXpm.(a|so) not found.

Fix: yum install libXpm-devel


checking for bind_textdomain_codeset in -lc… yes checking for GNU MP support… yes configure: error: Unable to locate gmp.h

Fix: yum install gmp-devel


checking for utf8_mime2text signature… new checking for U8T_DECOMPOSE… configure: error: utf8_mime2text() has new signature, but U8T_CANONICAL is missing. This should not happen. Check config.log for additional information.

Fix: yum install libc-client-devel


checking for LDAP support… yes, shared checking for LDAP Cyrus SASL support… yes configure: error: Cannot find ldap.h

Fix: yum install openldap-devel


checking for mysql_set_character_set in -lmysqlclient… yes checking for mysql_stmt_next_result in -lmysqlclient… no checking for Oracle Database OCI8 support… no checking for unixODBC support… configure: error: ODBC header file ‘/usr/include/sqlext.h’ not found!

Fix:yum install unixODBC-devel


checking for PostgreSQL support for PDO… yes, shared checking for pg_config… not found configure: error: Cannot find libpq-fe.h. Please specify correct PostgreSQL installation path

Fix: yum install postgresql-devel


checking for sqlite 3 support for PDO… yes, shared checking for PDO includes… (cached) /usr/local/src/php-5.3.7/ext checking for sqlite3 files in default path… not found configure: error: Please reinstall the sqlite3 distribution

Fix: yum install sqlite-devel


checking for utsname.domainname… yes checking for PSPELL support… yes configure: error: Cannot find pspell

Fix: yum install aspell-devel


checking whether to enable UCD SNMP hack… yes checking for default_store.h… no

checking for kstat_read in -lkstat… no checking for snmp_parse_oid in -lsnmp… no checking for init_snmp in -lsnmp… no configure: error: SNMP sanity check failed. Please check config.log for more information.

Fix: yum install net-snmp-devel


checking whether to enable XMLWriter support… yes, shared checking for xml2-config path… (cached) /usr/bin/xml2-config checking whether libxml build works… (cached) yes checking for XSL support… yes, shared configure: error: xslt-config not found. Please reinstall the libxslt >= 1.1.0 distribution

Fix: yum install libxslt-devel


configure: error: xml2-config not found. Please check your libxml2 installation.

Fix: yum install libxml2-devel


checking for PCRE headers location… configure: error: Could not find pcre.h in /usr

Fix: yum install pcre-devel


configure: error: Cannot find MySQL header files under yes. Note that the MySQL client library is not bundled anymore!

Fix: yum install mysql-devel


checking for unixODBC support… configure: error: ODBC header file ‘/usr/include/sqlext.h’ not found!

Fix: yum install unixODBC-devel


checking for pg_config… not found configure: error: Cannot find libpq-fe.h. Please specify correct PostgreSQL installation path

Fix:yum install postgresql-devel


configure: error: Cannot find pspell

Fix: yum install pspell-devel


configure: error: Could not find net-snmp-config binary. Please check your net-snmp installation.

Fix: yum install net-snmp-devel


configure: error: xslt-config not found. Please reinstall the libxslt >= 1.1.0 distribution

Fix: yum install libxslt-devel

 

编译安装PDO_MYSQL拓展模块,总是提示

这里写图片描述


这是因为这是因为在编译时需要 MySQL 的头的文件。而它按默认搜索找不到头文件的位置,所以才出现这个问题。通过软连接把MySQL头文件对应到/usr/local/include/下就好

比如你的MySQL安装文件位于/usr/local/mysql,那么就执行以下命令:

# ln -s /usr/local/mysql/include/* /usr/local/include/

当一个人找不到出路的时候,最好的办法就是将当前能做好的事情做到极致,做到无人能及。

3.微信小程序的开发

   1.编写websocket服务程序

    // 建立websocket 服务,启用9502端口
  $ws = new swoole_websocket_server("192.168.94.155", 9502);
	//监听链接
$ws->on('open', function ($ws, $request) {
    var_dump($request->fd, $request->get, $request->server);
    $ws->push($request->fd, "hello, welcome\n");
});
     //监听消息,这里就直接回显
$ws->on('message', function ($ws, $frame) {
    echo "Message: {$frame->data}\n";
    $ws->push($frame->fd, "server: {$frame->data}");
});
	// 关闭
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();

 

2.在服务上启动。输入phpwebsocket.php

这里写图片描述

3.开发微信小程序websocket客户端

Web-socket.js 代码:

  var socketOpen=false;
var  socketMsgQueue = [];
Page({
  data:{
    items:[

    ],

  },
    onReady: function() {
   wx.connectSocket({
   url:"ws://192.168.94.155:9502",
  success:function(res)
  {
    console.log('ok');
    wx.onSocketOpen(function(res){
    socketOpen=true;
    for(var i = 0 ; i <socketMsgQueue.length; i++){
 	    this.sendSocketMessage( socketMsgQueue[i])
     }
    socketMsgQueue = [];
    }),
    wx.onSocketMessage(function(res){

     var thisapp = getApp();
     var thispage = thisapp.getCurrentPage();
    var changedData ={}
    console.log( thispage.data.items.length);
    var index = thispage.data.items.length;
    changedData['items[' + index + '].text'] = res.data;
    thispage.setData(changedData)
    console.log("收到服务器内容:" + res.data)
    })
  },
  fail: function(res){
    console.log(res);
  }
    });
  },
 sendSocketMessage:function(msg)
 {
    if(socketOpen){
    wx.sendSocketMessage({
       data:msg
    });
  }else{
     socketMsgQueue.push(msg)
  }
 },
 bindSendMessage:function(e)
 {
    console.log(e);
    var msg =e.detail.value.msg;
    this.sendSocketMessage(msg);
 }


})
Web-socket.wxml:
<import src="../common/header.wxml" />
<import src="../common/footer.wxml" />

<view class="container">
  <template is="header" data="{{title: 'WebSocket'}}"/>
<form bindsubmit="bindSendMessage" bindreset="formReset">
  <view class="page-body">
    <view class="page-body-wording">
      <text class="page-body-text"  bindtap="sendSocketMessage" >
        搭建好自己的后台服务器后,可以跟服务器建立持久连接,实现即时聊天等功能。
      </text>
    </view>
    <view wx:for="{{items}}">
        {{index}}: {{item.text}}
    </view>

    <input placeholder="Your Message" focus="true" name="msg"   />
    <view class="btn-area">
        <button formType="submit" >Send</button>
    </view>
  </view>
</form>
  <template is="footer" />
</view>

最后结果如图:

这里写图片描述