# 1. 数据格式定义
暂定json数据格式定义为{"controller":"Im","action:"demo","param":{json数据}}(时间足够后续可能会改用pubutuf)
# 2. 数据测试
发送数据测试 如图 收到数据后进行解码以及转发数据到对应控制器![](https://i.loli.net/2019/03/11/5c862bba7d442.png)
# 3. 数据解码
在message回调中实现解码即可,代码如下,并实现抽象接口ParserInterface
```
//解码如下
$conf = new \EasySwoole\Socket\Config();
$conf->setType($conf::WEB_SOCKET);
$conf->setParser(new WebSocketParser);
$dispatch = new Dispatcher($conf);
$register->set(EventRegister::onMessage, function (\swoole_server $server, \swoole_websocket_frame $frame) use ($dispatch) {
$dispatch->dispatch($server, $frame->data, $frame);
});
```
实现抽象接口代码如下
```
namespace App\WebSocket;
use EasySwoole\Socket\AbstractInterface\ParserInterface;
use EasySwoole\Socket\Bean\Caller;
use EasySwoole\Socket\Bean\Response;
use EasySwoole\Socket\Client\WebSocket as WebSocketClient;
class WebSocketParser implements ParserInterface
{
/**
* 解码上来的消息
* @param string $raw 消息内容
* @param WebSocketClient $client 当前的客户端
* @return Caller|null
*/
public function decode($raw, $client): ?Caller
{
$caller = new Caller;
$payload = json_decode($raw, true);
$class = isset($payload['controller']) ? $payload['controller'] : 'ImController';
$action = isset($payload['action']) ? $payload['action'] : 'index';
$params = isset($payload['params']) ? (array)$payload['params'] : [];
$controllerClass = "\\App\\WsController\\" . ucfirst($class);
if (!class_exists($controllerClass)) $controllerClass = "\\App\\WsController\\ImController";
$caller->setClient($caller);
$caller->setControllerClass($controllerClass);
$caller->setAction($action);
$caller->setArgs($params);
return $caller;
}
/**
* 打包下发的消息
* @param Response $response 控制器返回的响应
* @param WebSocketClient $client 当前的客户端
* @return string|null
*/
public function encode(Response $response, $client): ?string
{
return $response->getMessage();
}
}
```
# 4. 测试解包后对应控制器方法是否能正常收发消息
创建ImController如图 打开http://www.easyswoole.com/wstool.html连接ws后发送消息如图所示
![](https://i.loli.net/2019/03/14/5c8a0bb3e001a.png)
![](https://i.loli.net/2019/03/14/5c8a0c7a4934b.png)
ImController代码如下
```<?php
/**
* Created by PhpStorm.
* User: pg
* Date: 19-3-14
* Time: 下午2:58
*/
namespace App\Controller\Ws;
use EasySwoole\Socket\AbstractInterface\Controller;
class ImController extends Controller
{
public function index(){
$client = $this->caller()->getClient();
$origin_param['fd'] = $client->getFd();
$origin_param['again_time'] = time();
$origin_param['send_count'] = 3;
$origin_param['msg'] = $this->caller()->getArgs();
$server = \EasySwoole\EasySwoole\ServerManager::getInstance()->getSwooleServer();
$server->push($client->getFd(),json_encode($origin_param));
}
}
```