用swoole搭建推送消息到小程序的服务器
2017-06-23 18:18
417 查看
环境
php7.1.3 (已安装 )centos7
安装 swoole
下载swoole然后
cd swoole phpize ./configure --enable-openssl (开启ssl) --enable-swoole --enable-sockets --enable-swoole-debug (开启debug,会在后台打印log,在生产环境不要开启) --with-php-config=/usr/local/php-7-1-3/bin/php-config make sudo make install
php 代码
<?php class ServerController { public function openAction() { $ws = new swoole_websocket_server("0.0.0.0", 9502, SWOOLE_BASE, SWOOLE_SOCK_TCP | SWOOLE_SSL);//SWOOLE_SSL 需要ssl才加 $ws->set(array( 'ssl_cert_file' => CERT_PATH.'/XXX.crt', 'ssl_key_file' => CERT_PATH.'/XXX.key', ));//如果需要 ssl的话 需要添加证书 否则去掉这段代码 //监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request) { $fd[] = $request->fd; $GLOBALS['fd'][] = $fd; $ws->push($request->fd, "hello, welcome\n"); }); //监听WebSocket消息事件 $ws->on('message', function ($ws, $frame) { $msg = 'from' . $frame->fd . ":{$frame->data}\n"; foreach ($GLOBALS['fd'] as $aa) { foreach ($aa as $i) { $ws->push($i, $msg); } } }); //监听WebSocket连接关闭事件 $ws->on('close', function ($ws, $fd) { echo "client-{$fd} is closed\n"; }); $ws->start(); } }
启动服务
$ php /here/cli/index.php request_uri="/socket/server/open" // 需要在cli的模式下启动
小程序代码
wx.connectSocket({ url: "wss://xxxxx:9502" }); wx.onSocketOpen(function (res) { console.log('WebSocket连接已打开!'); console.log(res); wx.sendSocketMessage({//发送测试数据 data: "mamamamama", complete: function (res) { console.log("sendSocketMessage"); console.log(res); } }); }); wx.onSocketError(function (res) { console.log('WebSocket连接打开失败,请检查!'); console.log(res); }); wx.onSocketMessage(function (res) { console.log('收到服务器内容:' + res.data) });
相关文章推荐
- iOS消息推送机制详解,APNS服务器搭建基本思路
- 通过Activemq搭建消息推送服务器实现局域网内android APP的消息推送
- 微信小程序 消息推送php服务器验证实例详解
- 用Swoole快速搭建一个推送服务器
- 服务器主动向android手机端推送消息---------Linux下Androidpn环境搭建
- 用 centrifugo 搭建 消息推送服务器 docker + rancher 搭建
- 微信小程序消息推送服务器接入
- 通过异步处理程序构建的长连接消息推送机制,单台服务器可以轻松支持上万个并发连接
- MPUSH消息推送服务器搭建
- 服务器主动向android手机端推送消息---------windows下Androidpn环境搭建
- 苹果消息推送服务器 php 证书生成
- 搭建XMPP协议,实现自主推送消息到手机
- web聊天程序,ajax+服务器推送技术
- android客户端之服务器消息推送
- 搭建XMPP协议,实现自主推送消息到手机
- 手机服务器Android消息推送(二)--基于MQTT协议实现的推送功能
- 基于XMPP协议(openfire服务器)的消息推送实现
- 异步消息总线hornetq学习-01基于maven的客户端程序框架搭建
- android中push机制实现:搭建XMPP协议,实现自主推送消息到手机
- Android 服务器消息推送技术