Swoole学习第三天,webscoket server 、task
前几天项目比较忙,今天继续学习
Swoole_webscoket_server
server端代码,测试的发现一个坑,可真的是坑死我了
<?php /** * Created by PhpStorm. * User: xuan_ * Date: 2019/10/23 * Time: 16:39 */ class Ws { const HOST = "0.0.0.0"; const PORT = "9502"; public $ws = null; public $_set = [ 'enable_static_handler' => true, //开启静态文件请求处理功能, 需配合document_root使用 'document_root' => "/data/www", //配置静态文件根目录,与enable_static_handler配合使用。 'worker_num' => 2, //设置启动的Worker进程数 //配置Task进程的数量,配置此参数后将会启用task功能。所以Server务必要注册onTask、onFinish2个事件回调函数。如果没有注册,服务器程序将无法启动。 'task_worker_num' => 2, ]; public function __construct() { $this->ws = new swoole_websocket_server(self::HOST, self::PORT); $this->ws->set($this->_set); $this->ws->on('open', [$this, 'onOpen']); $this->ws->on('message', [$this, 'onMessage']); $this->ws->on('task', [$this, 'onTask']); $this->ws->on('finish', [$this, 'onFinish']); $this->ws->on('close', [$this, 'onClose']); $this->ws->start(); } /** * 监听ws打开事件 * @param $ws * @param $request */ public function onOpen($ws, $request){ var_dump($request->fd); } /** * 监听ws消息事件 * @param $ws * @param $frame */ public function onMessage($ws, $frame){ echo "WS_server-push-message:".$frame->data ."\n"; $data = [ 'task' => 1, 'fd' => $frame->fd, ]; $ws->task($data); $ws->push($frame->fd, "server-push:".date('Y-m-d H:i:s')."\n"); } /**
* 投递一个异步任务到task_woker 中 * 在task_worker进程内被调用。worker进程可以使用swoole_server_task函数向task_worker进程投递新的任务。 * 当前的Task进程在调用onTask回调函数时会将进程状态切换为忙碌,这时将不再接收新的Task,当onTask函数返回时会将进程状态切换为空闲然后继续接收新的Task。 * @param $ws * @param $task_id * @param $work_id * @param $data * @return string */
public function onTask($ws, $task_id, $work_id, $data){ print_r($data); sleep(10); return 'on task '.$task_id.' 10s'."\n"; //告诉worker进程 } /** * 当worker进程投递的任务在task_worker中完成时,task进程会通过swoole_server->finish()方法将任务处理的结果发送给worker进程。 * @param $ws * @param $taskId * @param $data */ public function onFinish($ws, $taskId, $data){ echo "taskId:{$taskId}\n"; echo "finish-data-sucess:{$data}\n"; } /** * 关闭客户端 * @param $ws * @param $fd */ public function onClose($ws, $fd){ echo 'closeClient:'.$fd."\n"; } } $obj = new Ws();
client端代码
<html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>WS Client</h1> <script> var wsUrl = "ws://127.0.0.1:9502"; var ws = new WebSocket(wsUrl); ws.onopen = function (evt) { ws.send('hello swoole'); console.log('conected-success'); }; ws.onmessage = function (evt) { console.log('ws-server return' + evt.data); } ws.onclose = function (evt) { console.log('close'); } ws.onerror = function (evt,e) { console.log('error:' + e.error + '\n'); } </script> </body> </html>
碰到一个错误: WebSocket connection to 'ws://127.0.0.1:9502/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSE
这个错误是因为我在云服务器运行的 在本地电脑访问html文件,所以一直没办法建立正确链接webscoket,这里
var wsUrl = "ws://127.0.0.1:9502";
要写成云服务器的IP才可以正确访问,还有记得端口要开放,还有防火墙设置