配置文件 config/swoole.php
<?php
//默认\think\swoole\websocket\Handler::class,
use think\swoole\websocket\socketio\Handler;
return [
'http' => [
'enable' => true,//开启
'host' => '0.0.0.0',
'port' => 9501,
'worker_num' => swoole_cpu_num(),
'options' => [],
],
'websocket' => [
'enable' => true,//开启
'handler' => Handler::class,
'ping_interval' => 25000,
'ping_timeout' => 60000,
'room' => [
'type' => 'table',
'table' => [
'room_rows' => 8192,
'room_size' => 2048,
'client_rows' => 4096,
'client_size' => 2048,
],
'redis' => [
'host' => '127.0.0.1',
'port' => 6379,
'max_active' => 3,
'max_wait_time' => 5,
],
],
'listen' => [
'event' => \app\listener\WebsocketTest::class,//事件监听
],
'subscribe' => [],
],
];
事件监听app\listener\WebsocketTest
<?php
declare (strict_types = 1);
namespace app\listener;
use think\Container;
use think\swoole\Websocket;
class WebsocketTest
{
public $websocket = null;
public function __construct(Container $container){
$this->websocket = $container->make(Websocket::class);
}
/**
* 事件监听处理
* @param $event
*/
public function handle($event)
{
$func = $event->type;
$this->$func($event);
}
/**
* 测试类型
* @param $event
*/
public function test($event)
{
$msg = json_encode($event->data,256);
$this->websocket->emit('callback', $msg);
}
}
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.socket.io/socket.io-1.4.4.js"></script>
</head>
<body>
<script>
var socket = io('http://IP:9501',{transports: ['websocket']});
//对应事件 以及消息
socket.emit("test",{"asd":"我是内容"})
//回调事件
socket.on('callback',(data)=>{
console.log('data',data);
});
</script>
</body>
</html>
启动swoole
php think swoole
标签:thinkphp8,websocket,socket,swoole,event,swoole4.0,data,think
From: https://www.cnblogs.com/douyuanjun/p/18053789