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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
<?php
namespace console\controllers;
use Workerman\Worker;
use yii\helpers\Console;
use yii\console\Controller;
use Workerman\Protocols\Websocket;
class WorkermanWebSocketController extends Controller
{
public $send;
public $daemon;
public $gracefully;
// 这里不需要设置,会读取配置文件中的配置
public $config = [];
private $ip = '0.0.0.0';
private $port = '8080';
public function options($actionID)
{
return ['send', 'daemon', 'gracefully'];
}
public function optionAliases()
{
return [
's' => 'send',
'd' => 'daemon',
'g' => 'gracefully',
];
}
public function actionIndex()
{
if ('start' == $this->send) {
try {
$this->start($this->daemon);
} catch (\Exception $e) {
$this->stderr($e->getMessage() . "\n", Console::FG_RED);
}
} else if ('stop' == $this->send) {
$this->stop();
} else if ('restart' == $this->send) {
$this->restart();
} else if ('reload' == $this->send) {
$this->reload();
} else if ('status' == $this->send) {
$this->status();
} else if ('connections' == $this->send) {
$this->connections();
}
}
public function initWorker()
{
$ip = isset($this->config['ip']) ? $this->config['ip'] : $this->ip;
$port = isset($this->config['port']) ? $this->config['port'] : $this->port;
define('HEARTBEAT_TIME', 5);
$wsWorker = new Worker("websocket://{$ip}:{$port}");
// 4 processes
$wsWorker->count = 4;
$wsWorker->uidConnections = [];
global $uids;
// Emitted when new connection come
$wsWorker->onConnect = function ($connection) {
echo "New connection\n";
};
// $wsWorker->onConnect = function($connection) {
// // 给链接对象临时赋值一个lastTime属性记录上次接收消息的时间
// $connection->lastTime = time();
// };
// 进程启动后设置一个每秒运行一次的定时器
$wsWorker->onWorkerStart = function ($worker) {
\Workerman\Lib\Timer::add(1, function () use ($worker) {
$time_now = time();
foreach ($worker->connections as $connection) {
// 有可能该connection还没收到过消息,则lastMessageTime设置为当前时间
if (empty($connection->lastMessageTime)) {
$connection->lastMessageTime = $time_now;
continue;
}
// 上次通讯时间间隔大于心跳间隔,则认为客户端已经下线,关闭连接
if ($time_now - $connection->lastMessageTime > HEARTBEAT_TIME) {
$connection->close();
}
}
});
};
// Emitted when data received
$wsWorker->onMessage = function ($connection, $data) {
if ('binance' == $data) {
$con = new \Workerman\Connection\AsyncTcpConnection("ws://stream.binance.com:9443/ws/!ticker@arr");
$con->transport = 'ssl';
$con->onMessage = function ($con, $data) use ($connection) {
$base_coin = [
'ETH', 'BTC', 'USDT', 'BTY'
];
$result = json_decode($data, true);
$ticker = [];
foreach ($result as $val) {
foreach ($base_coin as $k => $coin) {
$explode_arr = explode($coin, $val['s']);
if (2 == count($explode_arr) && empty($explode_arr[1])) {
$temp = [];
$temp['symbol'] = $explode_arr[0] . '/' . $coin;
$temp['close'] = (float)sprintf("%0.4f", $val['c']);
$temp['change'] = (float)sprintf("%0.4f", $val['p'] * 100);
$temp['high'] = (float)sprintf("%0.4f", $val['h']);
$temp['low'] = (float)sprintf("%0.4f", $val['l']);
$temp['vol'] = (float)sprintf("%0.4f", $val['v']);
array_push($ticker, $temp);
break;
}
}
}
$connection->send('binance : ' . json_encode($ticker));
};
$con->connect();
} elseif ('huobi' == $data) {
//$connection->websocketType = Websocket::BINARY_TYPE_ARRAYBUFFER;
// ssl需要访问443端口
$con = new \Workerman\Connection\AsyncTcpConnection('ws://api.huobi.pro:443/ws');
// 设置以ssl加密方式访问,使之成为wss
$con->transport = 'ssl';
$con->onConnect = function ($con) {
$data = json_encode([
#'sub' => 'market.btcusdt.kline.1min',
#'id' => 'depth' . time(),
'sub' => 'market.overview'
]);
$con->send($data);
};
$con->onMessage = function ($con, $data) use ($connection) {
$data = gzdecode($data);
$data = json_decode($data, true);
if (isset($data['ping'])) {
$con->send(json_encode([
"pong" => $data['ping']
]));
} else if (isset($data['ch']) && 'market.overview' == $data['ch']) {
$base_coin = [
'ETH', 'BTC', 'USDT', 'BTY'
];
$ticker = [];
foreach ($data['data'] as $val) {
foreach ($base_coin as $k => $coin) {
$explode_arr = explode($coin, strtoupper($val['symbol']));
if (2 == count($explode_arr) && empty($explode_arr[1])) {
$temp = [];
$temp['symbol'] = $explode_arr[0] . '/' . $coin;
$temp['close'] = (float)sprintf("%0.4f", $val['close']);
$temp['change'] = (0 == $val['open']) ? 0 : (float)sprintf("%0.4f", ($val['close'] - $val['open']) / $val['open'] * 100);
$temp['high'] = (float)sprintf("%0.4f", $val['high']);
$temp['low'] = (float)sprintf("%0.4f", $val['low']);
$temp['vol'] = (float)sprintf("%0.4f", $val['vol']);
array_push($ticker, $temp);
break;
}
}
}
$connection->send('huobi : ' . json_encode($ticker));
} else {
}
};
$con->connect();
} elseif ('okex' == $data) {
$connection->websocketType = Websocket::BINARY_TYPE_ARRAYBUFFER;
$con = new \Workerman\Connection\AsyncTcpConnection("ws://real.okex.com:8443/ws/v3");
$con->transport = 'ssl';
$con->onConnect = function ($con) {
$data = json_encode([
'op' => 'subscribe',
'args' => [
'spot/all_ticker_3s',
'futures/all_ticker_3s',
'index/all_ticker_3s',
'futures/delivery:BTC'
]
]);
$con->send("{\"op\":\"subscribe\",\"args\":[\"spot/all_ticker_3s\",\"futures/all_ticker_3s\",\"index/all_ticker_3s\",\"futures/delivery:BTC\"]}");
};
$con->onMessage = function ($con, $data) use ($connection) {
$data = gzdecode($data);
$connection->send(date("Y-m-d H:i:s") . ' : ' . json_encode($data));
};
$con->connect();
} else {
$connection->send('other');
}
};
// Emitted when connection closed
$wsWorker->onClose = function ($connection) {
echo "Connection closed\n";
};
}
/**
* workman websocket start
*/
public function start()
{
$this->initWorker();
// 重置参数以匹配Worker
global $argv;
$argv[0] = $argv[1];
$argv[1] = 'start';
if ($this->daemon) {
$argv[2] = '-d';
}
// Run worker
Worker::runAll();
}
/**
* workman websocket restart
*/
public function restart()
{
$this->initWorker();
// 重置参数以匹配Worker
global $argv;
$argv[0] = $argv[1];
$argv[1] = 'restart';
if ($this->daemon) {
$argv[2] = '-d';
}
if ($this->gracefully) {
$argv[2] = '-g';
}
// Run worker
Worker::runAll();
}
/**
* workman websocket stop
*/
public function stop()
{
$this->initWorker();
// 重置参数以匹配Worker
global $argv;
$argv[0] = $argv[1];
$argv[1] = 'stop';
if ($this->gracefully) {
$argv[2] = '-g';
}
// Run worker
Worker::runAll();
}
/**
* workman websocket reload
*/
public function reload()
{
$this->initWorker();
// 重置参数以匹配Worker
global $argv;
$argv[0] = $argv[1];
$argv[1] = 'reload';
if ($this->gracefully) {
$argv[2] = '-g';
}
// Run worker
Worker::runAll();
}
/**
* workman websocket status
*/
public function status()
{
$this->initWorker();
// 重置参数以匹配Worker
global $argv;
$argv[0] = $argv[1];
$argv[1] = 'status';
if ($this->daemon) {
$argv[2] = '-d';
}
// Run worker
Worker::runAll();
}
/**
* workman websocket connections
*/
public function connections()
{
$this->initWorker();
// 重置参数以匹配Worker
global $argv;
$argv[0] = $argv[1];
$argv[1] = 'connections';
// Run worker
Worker::runAll();
}
}