<?php
/**
* Created by PhpStorm.
* User: season
* Date: 18-4-3
* Time: 下午5:55
*/
class SW
{
CONST HOST = '0.0.0.0';
CONST PORT = 9501;
public $sw = null;
public $set = [
'worker_num' => 2, //worker process num
'task_worker_num' => 2, //worker process num
'document_root' => '/home/season/Desktop/swoole/demo/temp',
'enable_static_handler' => true,
];
public function __construct()
{
$this->sw = new swoole_websocket_server(self::HOST, self::PORT);
$this->sw->set($this->set);
$this->sw->on('open', [$this, 'onOpen']);
$this->sw->on('message', [$this, 'onMessage']);
$this->sw->on('task', [$this, 'onTask']);
$this->sw->on('finish', [$this, 'onFinish']);
$this->sw->on('close', [$this, 'onClose']);
$this->sw->start();
}
//监听websocket 打开/连接 事件
//当WebSocket客户端与服务器建立连接并完成握手后会回调此方法。
public function onOpen($server, $request)
{
echo "服务器: 握手成功,fd{$request->fd}\n";
}
//当WebSocket客户端与服务器建立连接并完成握手后会回调此函数。
public function onMessage($server, $frame)
{
echo "收到 {$frame->fd}:{$frame->data},操作码:{$frame->opcode},完成:{$frame->finish}\n";
$data = [
'task' => 1,
'fd' => $frame->fd,
];
$server->task($data);
$redisClient = new Swoole\Redis();
$redisClient->connect('127.0.0.1',6379,function (swoole_redis $swoole_redis ,$result)use ($frame) {
$swoole_redis->set($frame->fd,true,function (swoole_redis $swoole_redis,$result){});
$swoole_redis->keys('*',function (swoole_redis $swoole_redis,$result) use($frame){
print_r($result);
foreach ($result as $fd) {
$this->sw->push($fd, '用户'.$frame->fd.'已登录');
}
});
});
}
//任务
public function onTask($server, $task_id, $src_worker_id, $data)
{
//print_r($data);
$data['msg'] = '任务完成';
sleep(10);
return json_encode($data);
}
/**
* @param $server
* @param $task_id 任务的ID
* @param $data onTask return返回的数据
*/
public function onFinish($server, $task_id, $data)
{
$data = json_decode($data);
//echo "任务编号:{$task_id},{$data->msg}\n";
$server->push($data->fd, "任务编号:{$task_id},{$data->msg}\n");
}
//关闭时出发回调
public function onClose($server, $fd)
{
echo "客户端: {$fd} 已关闭\n";
}
}
new SW();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>swoole-websocket</title>
</head>
<body>
</body>
<script>
var wsUrl = 'ws://127.0.0.1:9501';
var websocket = new WebSocket(wsUrl);
//实例化成功
websocket.onopen = function (evt) {
console.log('连接成功!\n');
websocket.send('hello');
}
//实例化成功
websocket.onmessage = function (evt) {
console.log('接收到服务器返回数据:' + evt.data +'\n');
}
//实例化成功
websocket.onclose = function (evt) {
console.log('已关闭\n');
}
//实例化成功
websocket.onerror = function (evt,e) {
console.log('错误:'+ evt.data +'\n');
}
</script>
</html>