使用ThinkPHP实现WebSocket通信需要安装Swoole扩展,然后在ThinkPHP中创建一个Swoole服务器。具体步骤如下:
pecl install swoole
在ThinkPHP项目中创建一个Swoole服务器,可以通过继承think\swoole\Server类来实现。
namespace app\index\controller;
use think\swoole\Server;
class WebSocket extends Server
{
protected $host = '0.0.0.0';
protected $port = 9501;
protected $serverType = 'socket';
protected $option = [
'worker_num' => 4,
];
public function onOpen($server, $request)
{
echo "server: handshake success with fd{$request->fd}\n";
}
public function onMessage($server, $frame)
{
echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
$server->push($frame->fd, "this is server");
}
public function onClose($server, $fd)
{
echo "client {$fd} closed\n";
}
}
在上面的代码中,$host和$port指定了服务器的地址和端口,$serverType指定了服务器的类型,option数组中指定了服务器的参数。onOpen、onMessage和onClose分别是WebSocket服务器的三个回调函数。
使用命令行进入ThinkPHP项目的根目录,运行以下命令启动Swoole服务器:
php think swoole:server start
在前端页面中,使用WebSocket对象连接到Swoole服务器,并在连接成功后发送消息。
var ws = new WebSocket("ws://127.0.0.1:9501");
ws.onopen = function() {
ws.send("Hello, Swoole!");
};
ws.onmessage = function(evt) {
console.log("receive from server: " + evt.data);
};
ws.onclose = function() {
console.log("WebSocket closed");
};
以上就是使用ThinkPHP实现WebSocket通信的步骤。需要注意的是,在使用Swoole扩展时,需要开启swoole扩展中的websocket协议,可以通过修改php.ini文件或在命令行中使用-s参数指定。