作者:BruceCCCC,来自原文地址
以下为关键代码:
PHP代码
-
<?php
-
namespace app\socket\controller;
-
use Workerman\Worker;
-
use Workerman\Connection\TcpConnection;
-
use Workerman\Lib\Timer;
-
-
-
class Index
-
{
-
public function index()
-
{
-
-
// 证书最好是申请的证书
-
$context = array(
-
'ssl' => array(
-
// 使用绝对路径
-
'local_cert' => 'E:\ssl\214060279060404.pem', // 也可以是crt文件
-
'local_pk' => 'E:\ssl\214060279060404.key',
-
'verify_peer' => false,
-
)
-
);
-
// 这里设置的是websocket协议
-
$worker = new Worker('websocket://0.0.0.0:4431', $context);
-
// 设置transport开启ssl,websocket+ssl即wss
-
$worker->transport = 'ssl';
-
$worker->onMessage = function($con, $msg) {
-
$con->send('ok');
-
};
-
-
Worker::runAll();
-
-
}
-
}
js代码
-
wx.connectSocket({
-
url: 'wss://www.candy123.top:4431'
-
});
-
-
wx.onSocketOpen(function(res) {
-
console.log("连接成功");
-
wx.sendSocketMessage('tom');
-
console.log("给服务端发送一个字符串:tom");
-
});
-
-
wx.onSocketMessage(function(res) {
-
console.log("收到服务端的消息:" + res.data);
-
});
|