金华
作者:互联网
一、创建http服务器
- <?php
- //创建http对象
- $httpServer = new swoole_http_server('0.0.0.0', 80);
- //监听端口请求
- $httpServer->on('request', function($request, $response) {
- //请求
- var_dump($request);
- //分隔符
- echo "------------------------\r\n";
- //响应
- var_dump($response);
- //响应内容
- $response->end('help');
- });
- //启动服务器
- $httpServer->start();
二、创建websocket服务
- <?php
- //创建websocket服务
- $server = new swoole_websocket_server('0.0.0.0', 8003);
- //握手成功,触发回调函数
- $server->on('open', function(swoole_websocket_server $server, $request) {
- echo "server: handshark success with fd{$request->fd}\r\n";
- });
- //收到消息,触发回调函数
- $server->on('message', function(swoole_websocket_server $server, $frame) {
- echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\r\n";
- $server->push($frame->fd, 'i accept your message');
- });
- //关闭链接时,触发的函数
- $server->on('close', function($ser, $fd) {
- echo "client {$fd} closed\r\n";
- });
- //启动websocket服务器
- $server->start();
三、swoole操作进程
- <?php
- //设置主进程名称
- swoole_set_process_name("swoole_master_process");
- $worker = new swoole_process(function() {
- //设置子进程名称
- swoole_set_process_name("swoole_son_process");
- sleep(10);
- });
- //运行子进程
- $worker->start();
- //因为子进程需要等待10s,所以父进程比子进程先执行完,因此父进程要等子进程执行完,防止出现孤儿进程
- swoole_process::wait();
四、毫秒级延时器
- <?php
- swoole_timer_after(3000, function() {
- echo "123\r\n";
- });
- echo "456\r\n";
五、毫秒级定时器
- <?php
- swoole_timer_tick(3000, function() {
- echo "当前时间为: " . date('Y-m-d H:i:s') . "\r\n";
- });
六、异步操作文件
- <?php
- echo "123\r\n";
- swoole_async_readfile('./test.txt', function($filename, $content) {
- echo "{$filename}: {$content}";
- });
标签:function,websocket,swoole,frame,echo,server,金华 来源: https://www.cnblogs.com/rgt45/p/14257027.html