swoole 测试

安装PHP

安装sowoole 扩展

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
➜  package cd swoole
➜ swoole git:(master) phpize
Configuring for:
PHP Api Version: 20170718
Zend Module Api No: 20170718
Zend Extension Api No: 320170718
➜ swoole git:(master) ./configure
➜ swoole git:(master) make && make installs

···
Build complete.
Don't forget to run 'make test'.

Installing shared extensions: /usr/local/Cellar/php@7.2/7.2.16/pecl/20170718/
Installing header files: /usr/local/Cellar/php@7.2/7.2.16/include/php/

ws_server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
<?php
class Ws {
CONST HOST = "0.0.0.0";
CONST PORT = 8811;
CONST CHART_PORT = 8812;

public $ws = null;
public function __construct() {
// 获取 key 有值 del
$this->ws = new swoole_websocket_server(self::HOST, self::PORT);
$this->ws->listen(self::HOST, self::CHART_PORT, SWOOLE_SOCK_TCP);

$this->ws->set(
[
'enable_static_handler' => true,
'document_root' => "/home/work/hdtocs/swoole_mooc/thinkphp/public/static",
'worker_num' => 4,
'task_worker_num' => 4,
]
);

$this->ws->on("start", [$this, 'onStart']);
$this->ws->on("open", [$this, 'onOpen']);
$this->ws->on("message", [$this, 'onMessage']);
$this->ws->on("workerstart", [$this, 'onWorkerStart']);
$this->ws->on("request", [$this, 'onRequest']);
$this->ws->on("task", [$this, 'onTask']);
$this->ws->on("finish", [$this, 'onFinish']);
$this->ws->on("close", [$this, 'onClose']);

$this->ws->start();
}

/**
* @param $server
*/
public function onStart($server) {
swoole_set_process_name("live_master");
}
/**
* @param $server
* @param $worker_id
*/
public function onWorkerStart($server, $worker_id) {
// 定义应用目录
define('APP_PATH', __DIR__ . '/../../../application/');
// 加载框架里面的文件
//require __DIR__ . '/../thinkphp/base.php';
require __DIR__ . '/../../../thinkphp/start.php';
}

/**
* request回调
* @param $request
* @param $response
*/
public function onRequest($request, $response) {
if($request->server['request_uri'] == '/favicon.ico') {
$response->status(404);
$response->end();
return ;
}
$_SERVER = [];
if(isset($request->server)) {
foreach($request->server as $k => $v) {
$_SERVER[strtoupper($k)] = $v;
}
}
if(isset($request->header)) {
foreach($request->header as $k => $v) {
$_SERVER[strtoupper($k)] = $v;
}
}

$_GET = [];
if(isset($request->get)) {
foreach($request->get as $k => $v) {
$_GET[$k] = $v;
}
}
$_FILES = [];
if(isset($request->files)) {
foreach($request->files as $k => $v) {
$_FILES[$k] = $v;
}
}
$_POST = [];
if(isset($request->post)) {
foreach($request->post as $k => $v) {
$_POST[$k] = $v;
}
}

$this->writeLog();
$_POST['http_server'] = $this->ws;


ob_start();
// 执行应用并响应
try {
think\Container::get('app', [APP_PATH])
->run()
->send();
}catch (\Exception $e) {
// todo
}

$res = ob_get_contents();
ob_end_clean();
$response->end($res);
}

/**
* @param $serv
* @param $taskId
* @param $workerId
* @param $data
*/
public function onTask($serv, $taskId, $workerId, $data) {

// 分发 task 任务机制,让不同的任务 走不同的逻辑
$obj = new app\common\lib\task\Task;

$method = $data['method'];
$flag = $obj->$method($data['data'], $serv);
/*$obj = new app\common\lib\ali\Sms();
try {
$response = $obj::sendSms($data['phone'], $data['code']);
}catch (\Exception $e) {
// todo
echo $e->getMessage();
}*/

return $flag; // 告诉worker
}

/**
* @param $serv
* @param $taskId
* @param $data
*/
public function onFinish($serv, $taskId, $data) {
echo "taskId:{$taskId}\n";
echo "finish-data-sucess:{$data}\n";
}

/**
* 监听ws连接事件
* @param $ws
* @param $request
*/
public function onOpen($ws, $request) {
// fd redis [1]
\app\common\lib\redis\Predis::getInstance()->sAdd(config('redis.live_game_key'), $request->fd);
var_dump($request->fd);
}

/**
* 监听ws消息事件
* @param $ws
* @param $frame
*/
public function onMessage($ws, $frame) {
echo "ser-push-message:{$frame->data}\n";
$ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s"));
}

/**
* close
* @param $ws
* @param $fd
*/
public function onClose($ws, $fd) {
// fd del
\app\common\lib\redis\Predis::getInstance()->sRem(config('redis.live_game_key'), $fd);
echo "clientid:{$fd}\n";
}

/**
* 记录日志
*/
public function writeLog() {
$datas = array_merge(['date' => date("Ymd H:i:s")],$_GET, $_POST, $_SERVER);

$logs = "";
foreach($datas as $key => $value) {
$logs .= $key . ":" . $value . " ";
}

swoole_async_writefile(APP_PATH.'../runtime/log/'.date("Ym")."/".date("d")."_access.log", $logs.PHP_EOL, function($filename){
// todo
}, FILE_APPEND);

}
}

new Ws();

ws_client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>singwa-swoole-ws测试<h1>
<script>
var wsUrl = "ws://swoole.demo.com:8812";

var websocket = new WebSocket(wsUrl);

//实例对象的onopen属性
websocket.onopen = function(evt) {
websocket.send("hello-sinwa");
console.log("conected-swoole-success");
}

// 实例化 onmessage
websocket.onmessage = function(evt) {
console.log("ws-server-return-data:" + evt.data);
}

//onclose
websocket.onclose = function(evt) {
console.log("close");
}
//onerror

websocket.onerror = function(evt, e) {
console.log("error:" + evt.data);
}

</script>
</body>
</html>

定时器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
class Server {
const PORT = 8811;

public function port() {
$shell = "netstat -anp 2>/dev/null | grep ". self::PORT . " | grep LISTEN | wc -l";

$result = shell_exec($shell);
if($result != 1) {
// 发送报警服务 邮件 短信
/// todo
echo date("Ymd H:i:s")."error".PHP_EOL;
} else {
echo date("Ymd H:i:s")."succss".PHP_EOL;
}
}
}

// nohup
swoole_timer_tick(2000, function($timer_id) {
(new Server())->port();
echo "time-start".PHP_EOL;
});