1. Go to this page and download the library: Download topthink/think-swoole library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
topthink / think-swoole example snippets
Route::get('static/:path', function (string $path) {
$filename = public_path() . $path;
return new \think\swoole\response\File($filename);
})->pattern(['path' => '.*\.\w+$']);
use \think\swoole\Websocket;
use \think\swoole\websocket\Event;
use \Swoole\WebSocket\Frame;
use \think\swoole\websocket\Room;
class Controller {
public function action1(){//不可以在这里注入websocket对象
return \think\swoole\helper\websocket()
->onOpen(...)
->onMessage(function(Websocket $websocket, Frame $frame){ //只可在事件响应这里注入websocket对象
//...
$websocket->join('room_key'); //将当前连接加入到某个room,后续可以向该room发送消息 这个room里的都可以收到
//比如room_key可以直接使用这个用户的id,然后其他地方需要给某个用户发送消息,直接向这个room发送消息即可
//...
$websocket->push('message'); //给当前连接发送消息
//...
$websocket->emit('event_name', 'message'); //给当前连接发送事件
//...
$websocket->to('room_key')->push('message'); //给指定room的所有连接发送消息 在http请求的控制器中也可以注入Websocket对象这样发消息
//...
})
->onClose(...);
}
public function action2(){
return \think\swoole\helper\websocket()
->onOpen(...)
->onMessage(function(Websocket $websocket, Frame $frame){
//...
})
->onClose(...);
}
}
class Controller {
public function action(){
return \think\swoole\helper\iterator(value(function(){
foreach(range(1,10) as $i)
yield $i;
sleep(1);//模拟等待
}
}));
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.