您的位置:首页 > 移动开发 > 微信开发

用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)
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ssl php swoole 服务器