嗯~ o(* ̄▽ ̄*)o,没错欢迎收看继续爬坑系列233...话不多说直接开撸

今天的题材是websocket,没有特殊说明的话默认环境都和此系列第一篇文章中申明一致,此后不再赘述。

websocket相关知识:

http://www.ruanyifeng.com/blog/2017/05/websocket.html

一、配置文件及源码解读

swoole.php

use Swoole\WebSocket\Server;
use think\facade\Env;// +----------------------------------------------------------------------
// | Swoole设置 php think swoole命令行下有效
// +----------------------------------------------------------------------
return [
// 扩展自身配置
'host' => '0.0.0.0', // 监听地址
'port' => 9501, // 监听端口
'mode' => '', // 运行模式 默认为SWOOLE_PROCESS
'sock_type' => '', // sock type 默认为SWOOLE_SOCK_TCP
'server_type' => 'websocket', // 服务类型 支持 http websocket
'app_path' => '', // 应用地址 如果开启了 'daemonize'=>true 必须设置(使用绝对路径)
'file_monitor' => false, // 是否开启PHP文件更改监控(调试模式下自动开启)
'file_monitor_interval' => 2, // 文件变化监控检测时间间隔(秒)
'file_monitor_path' => [], // 文件监控目录 默认监控application和config目录 // 可以支持swoole的所有配置参数
'pid_file' => Env::get('runtime_path') . 'swoole.pid',
'log_file' => Env::get('runtime_path') . 'swoole.log',
'document_root' => Env::get('root_path') . 'public',
'enable_static_handler' => true,
'timer' => true,//是否开启系统定时器
'interval' => 500,//系统定时器 时间间隔
'task_worker_num' => 1,//swoole 任务工作进程数量 /**
* 注意:系统内定义了Message,Close回调,在此配置的是不会执行滴
*/
'Open' => function (Server $server, $request) {
echo "server: handshake success with fd {$request->fd}\n";
}
];
系统内定义了Message,Close回调,在此配置的是不会执行滴(上源码)

vendor\topthink\think-swoole\src\Http.php

<?php

    public function option(array $option)
{
// 设置参数
if (!empty($option)) {
$this->swoole->set($option);
} foreach ($this->event as $event) {
// 自定义回调
if (!empty($option[$event])) {
$this->swoole->on($event, $option[$event]);
} elseif (method_exists($this, 'on' . $event)) {
$this->swoole->on($event, [$this, 'on' . $event]);
}
}
if ("websocket" == $this->server_type) {
foreach ($this->event as $event) {
if (method_exists($this, 'Websocketon' . $event)) {
$this->swoole->on($event, [$this, 'Websocketon' . $event]);
}
}
}
} /**
* Message回调
* @param $server
* @param $frame
*/
public function WebsocketonMessage($server, $frame)
{
// 执行应用并响应
$this->app->swooleWebSocket($server, $frame);
} /**
* Close
*/
public function WebsocketonClose($server, $fd, $reactorId)
{
$data = [$server, $fd, $reactorId];
$hook = Container::get('hook');
$hook->listen('swoole_websocket_on_close', $data);
}

看到标红的那段没,就算你设置了也会被覆盖掉,而是用内置的  WebsocketonMessage() 、WebsocketonClose() 这两个方法,不过不用担心,既然直接定义不可以那就绕一下呗。

先看 WebsocketonMessage() 会执行swooleWebSocket()方法:

vendor\topthink\think-swoole\src\Application.php

public function swooleWebSocket($server, $frame)
{
try {
// 重置应用的开始时间和内存占用
$this->beginTime = microtime(true);
$this->beginMem = memory_get_usage(); // 销毁当前请求对象实例
$this->delete('think\Request');
WebSocketFrame::destroy();
$request = $frame->data;
$request = json_decode($request, true); // 重置应用的开始时间和内存占用
$this->beginTime = microtime(true);
$this->beginMem = memory_get_usage();
WebSocketFrame::getInstance($server, $frame); $_COOKIE = isset($request['arguments']['cookie']) ? $request['arguments']['cookie'] : [];
$_GET = isset($request['arguments']['get']) ? $request['arguments']['get'] : [];
$_POST = isset($request['arguments']['post']) ? $request['arguments']['post'] : [];
$_FILES = isset($request['arguments']['files']) ? $request['arguments']['files'] : []; $_SERVER["PATH_INFO"] = $request['url'] ?: '/';
$_SERVER["REQUEST_URI"] = $request['url'] ?: '/';
$_SERVER["SERVER_PROTOCOL"] = 'http';
$_SERVER["REQUEST_METHOD"] = 'post'; // 重新实例化请求对象 处理swoole请求数据
$this->request
->withServer($_SERVER)
->withGet($_GET)
->withPost($_POST)
->withCookie($_COOKIE)
->withFiles($_FILES)
->setBaseUrl($request['url'])
->setUrl($request['url'])
->setHost(Config::get("app_host"))
->setPathinfo(ltrim($request['url'], '/')); // 更新请求对象实例
$this->route->setRequest($this->request); $resp = $this->run();
$resp->send(); } catch (HttpException $e) {
$this->webSocketException($server, $frame, $e);
} catch (\Exception $e) {
$this->webSocketException($server, $frame, $e);
} catch (\Throwable $e) {
$this->webSocketException($server, $frame, $e);
}
}

还是注意标红标粗的那几段,他把onMessage的参数传给了 WebSocketFrame 类,且从获取的参数看,传递参数是有要求的,继续走着

<?php
/**
* 参考think-swoole2.0开发
* author:xavier
* email:49987958@qq.com
* 可以配合https://github.com/xavieryang007/xavier-swoole/blob/master/src/example/websocketclient.js 使用
*/
namespace think\swoole; use think\Container; class WebSocketFrame implements \ArrayAccess
{
private static $instance = null;
private $server;
private $frame;
private $data; public function __construct($server, $frame)
{
$this->server = $server;
$this->data = null;
if (!empty($frame)) {
$this->frame = $frame;
$this->data = json_decode($this->frame->data, true);
}
} public static function getInstance($server = null, $frame = null)
{
if (empty(self::$instance)) {
if (empty($server)) {
$swoole = Container::get('swoole');
$server = $swoole;
}
self::$instance = new static($server, $frame);
}
return self::$instance;
} public static function destroy()
{
self::$instance = null;
} public function getServer()
{
return $this->server;
} public function getFrame()
{
return $this->frame;
} public function getData()
{
return $this->data;
} public function getArgs()
{
return isset($this->data['arguments']) ? $this->data['arguments'] : null;
} public function __call($method, $params)
{
return call_user_func_array([$this->server, $method], $params);
} public function pushToClient($data, $event = true)
{
if ($event) {
$eventname = isset($this->data['event']) ? $this->data['event'] : false;
if ($eventname) {
$data['event'] = $eventname;
}
}
$this->sendToClient($this->frame->fd, $data);
} public function sendToClient($fd, $data)
{
if (is_string($data)) {
$this->server->push($fd, $data);
} elseif (is_array($data)) {
$this->server->push($fd, json_encode($data));
}
} public function pushToClients($data)
{
foreach ($this->server->connections as $fd) {
$this->sendToClient($fd, $data);
}
} public function offsetSet($offset, $value)
{
$this->data[$offset] = $value;
} public function offsetExists($offset)
{
return isset($this->data[$offset]) ? true : false;
} public function offsetUnset($offset)
{
unset($this->data[$offset]);
} public function offsetGet($offset)
{
return isset($this->data[$offset]) ? $this->data[$offset] : null;
}
}

看源码后你发现,你要获取onMessage的数据,就需要用这个类咯。

再看 WebsocketonClose() 方法:

$hook->listen('swoole_websocket_on_close', $data);

直接是调用了 一个 swoole_websocket_on_close 钩子,那么这就好办了,咱只要添加这个钩子就能获取 onClose 的数据了。

二、实操

至此,就可以变向的自定义 onMessage, onClose 了,上个 demo....

Index.php 控制器 (自定义onMessage)

<?php

namespace app\index\controller;

use think\Controller;
use think\facade\Hook;
use think\swoole\WebSocketFrame; class Index extends Controller
{
// 自定义 onMessage
public function websocket()
{
$server = WebSocketFrame::getInstance()->getServer();
$frame = WebSocketFrame::getInstance()->getFrame();
$data = WebSocketFrame::getInstance()->getData();
$server->push($frame->fd, json_encode($data));
echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
// Hook::add('swoole_websocket_on_close', 'app\\http\\behavior\\SwooleWebsocketOnclose');
}
}

自定义 onClose

定义一个行为

<?php

namespace app\http\behavior;

class SwooleWebsocketOnClose
{
public function run($params)
{
list($server, $fd, $reactorId) = $params;
echo "client {$fd} closed\n";
}
}

再行为绑定

当系统执行

$hook->listen('swoole_websocket_on_close', $data);

时,就会调用行为中的 run() 方法。

三、执行

首先需要一个客户端:

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>websocket client</title>
</head>
<button type="button" id="send">发送</button>
<body>
<h1>swoole-ws测试</h1>
<script>
var wsUrl = 'ws://tp-live.test:9501';
var websocket = new WebSocket(wsUrl); websocket.onopen = function (evt) {
console.log("ws client 连接成功!");
}; document.getElementById('send').onclick = function () {
websocket.send('{"url":"index/index/websocket"}');
console.log('ws client 发送数据');
}; websocket.onmessage = function (evt) {
console.log("server return data: " + evt.data);
}; websocket.onclose = function (evt) {
console.log("connect close");
}; websocket.onerror = function (evt, e) {
console.log("error: " + evt.data);
}
</script>
</body> </html>

整个过程,服务端输出结果:

四、结束语

还有一种方法就是使用 swoole_server.php 的配置

具体方法可参照 : https://somsan.cc/archives/5a303a8b/

咳咳,保温杯里泡枸杞,书写不易,转载请申明出处 https://www.cnblogs.com/cshaptx4869/ 啦。。。

topthink/think-swoole 扩展包的使用 之 WebSocket的更多相关文章

  1. Ubuntu 16.04 swoole扩展安装注意!!!

    前言:目前很多项目估计常常会用到swoole扩展,如个人使用Ubuntu虚拟机安装扩展,这里总结一下遇到的问题: 一.先保证服务器时间同步当前地区时间,如北京时间: 1.设定时区 如:设定时区:dpk ...

  2. topthink/think-swoole 扩展包的使用 之 Task

    本想自己适配的,奈何keng貌似不少,所以果断选择官方提供的包来适配233... 默认条件:thinkphp5.1.*版本下,且安装了swoole扩展 主要演示:task 任务的投递 友情提示:在sw ...

  3. 【原】用PHP搭建基于swoole扩展的socket服务(附PHP扩展的安装步骤及Linux/shell在线手册)

    最近公司的一项目中,需要用PHP搭建一个socket服务. 本来PHP是不适合做服务的,因为和第三方合作,需要采用高效而稳定的TCP协议进行数据通信.经过多次尝试,最终选择了开源的PHP扩展:swoo ...

  4. Windows下用Composer引入官方GitHub扩展包

    Windows下用Composer引入官方GitHub扩展包 1. 当你打开威武RC4版本的链接的时候,往下拉你可以看到这个,然后你要做的就是想到,百度Composer,看看是个什么鬼,别想太多,跟着 ...

  5. Windows下swoole扩展的编译安装部署

    1. 到cygwin官网下载cygwin. 官网地址:https://www.cygwin.com/ 2. 打开下载好的cygwin安装包,开始安装cygwin. 选择cygwin的安装目录(这个同时 ...

  6. linux下搭建lamp环境以及安装swoole扩展

    linux下搭建lamp环境以及安装swoole扩展   一.CentOS 6.5使用yum快速搭建LAMP环境 准备工作:先更新一下yum源  我安装的环境是:apache2.2.15+mysql5 ...

  7. Mac系统下 PHP7安装Swoole扩展 教程

    转载自 https://www.fujieace.com/php/php-extensions/swoole.html 今天我用的PHP版本是:PHP7.1 环境依赖: php-5.3.10 或更高版 ...

  8. thinkphp5 Windows下用Composer引入官方GitHub扩展包

    很多新手,比如说我,写代码就是在windows下,所以总会遇到很多不方便的地方,比如说GitHub上面的代码更新了,要是你在linux,只要几行命令就可以搞定更新了,在windows下面,你需要用到C ...

  9. php swoole扩展安装

    一波三折. 首先下载swoole安装包(由于我这里php是7,所以说应该去官网下载最新的swoole包,否则会发生意想不到的错误) wget https://github.com/swoole/swo ...

随机推荐

  1. python ui自动化之元素定位和常用操作

    做ui自动化的最基础的就是页面元素定位了,如果连页面元素都定位不到,自动化从何谈起呢?接下来我们就看看页面元素定位的方法吧!(这里就用百度页面来进行演示) 一.最通用的几种定位方式: 1.通过id定位 ...

  2. 「NOIP2013」货车运输

    传送门 Luogu 解题思路 首先 \(\text{Kruskal}\) 一下,构造出一棵森林. 并查集还要用来判断连通性. 倍增 \(\text{LCA}\) 的时候顺便维护一下路径最小值即可. 细 ...

  3. docker aufs存储驱动文件系统

    Docker aufs存储驱动layer.diff.mnt目录的区别 /var/lib/docker/aufs layer子目录: 镜像.镜像历史列表.容器.容器INIT分别有对应的文件.文件名和di ...

  4. 部署java的spring boot项目(代码外包提供)

    部署java后台的spring boot 人脸识别系统的项目 基础环境准备: 硬件:内存4g  cpu 4核  硬盘200g  虚拟机 软件:CentOS 7.6  mysql 5.7.26  jdk ...

  5. Feign代理必须加value否则启动失败

    Feign代理必须加value否则启动失败 @RequestParam(value=”xxx”)

  6. Python基础入门语法1

    PY的交换值的方法 x.y = y.x PY既具有动态脚本的特性,又有面向对象的特性 PY的缺点: 编译型的语言(C++,C):通过编译器进行编译成机器码,越接近底层,开发效率低 解释型代码:PY和J ...

  7. excel表格 函数功能

    1.去重复 选中一个区域——>数据——>删除重复项 2.条件求和 按照条件筛选:筛选出一样的类目,将对应的值求和. =sumif(A$1:A$10,B2,C$1:C$10) A$1:A$1 ...

  8. centos解决bash: telnet: command not found...&& telnet: connect to address 127.0.0.1: Connection refused拒绝连接

    检查telnet是否已安装: [root@hostuser src]# rpm -q telnet-serverpackage telnet-server is not installed[root@ ...

  9. redis几种数据导出导入方式

    一.redis-dump方式 1.安装redis-dump工具 [root@172.20.0.3 ~]# yum install ruby rubygems ruby-devel -y 更改gem源 ...

  10. Vagrant 安装使用

    先安装虚拟机 https://www.virtualbox.org/ 再安装 https://www.vagrantup.com/  1.nginxhttp://nginx.org/download/ ...