[教程]微信小程序之websocket开发系列(一)

原创作者:direction
1.准备工作

l Centos 6.5建立的Wesocket服务器:

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

l 破解了的微信开发工具

l 微信小程序文档

2.Websocket搭建
2.1.Linux环境下安装

Linux操作系统通常都有自己的包管理软件(Ubuntu的apt-get,CentOS的yum,Mac OSX的HomeBrew等),因此一般情况下可以通过这些包管理软件直接安装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-openssl和with-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拓展模块,总是提示

article10-1.png

这是因为这是因为在编译时需要 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

article10-2.gif

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>

最后结果如图:


article10-3.gif

这里写图片描述

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容