swoole实现消息简单消息推送

我今生没有别的希望,我只希望,能多**几个女人。 ——季羡林 清华园日记

试验环境

  • ThinkPHP5
  • CentOS

后端php代码

tp5\application\console\TimerConsole.php

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
<?php
namespace App\Console;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Exception;


class TimerConsole extends Command
{
protected $server;
protected $client; // 用于保存所有的客户端

protected function configure()
{
$this->setName('timer:start')->setDescription('Start TCP(Timer) Server!');
}

protected function execute(Input $input, Output $output)
{
$this->server = new \swoole_websocket_server('0.0.0.0', 9501);

$this->server->on('open', function (\swoole_websocket_server $server, $request) {
echo "服务器: 握手成功-{$request->fd}\n";
$this->client[] = $request->fd;
echo json_encode($this->client);
});
$this->server->on('message', function (\swoole_websocket_server $server, $frame) {
echo "接受到消息: {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
foreach ($this->client as $item) {
if ($item) {
try {
$server->push($item, time());
} catch (Exception $exception) {
continue;
}
}
}
});
$this->server->on('close', function ($ser, $fd) {
echo "客户端关闭-{$fd}\n";
unset($this->client[$fd]);
});
$this->server->start();
}
}

前端html代码

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
if ("WebSocket" in window)
{
console.log("您的浏览器支持 WebSocket!");
var ws = new WebSocket("ws://vxndy.com:9501");
ws.onopen = function() {
ws.send("来自客户端的数据");
};

ws.onmessage = function (evt) {
var received_msg = evt.data;
console.log("数据已接收..."+received_msg);
document.getElementById("haha").innerHTML=received_msg;
};

ws.onclose = function() {
console.log("连接已关闭...");
};
}
else {
console.log("您的浏览器不支持 WebSocket!");
}
</script>
</head>
<body>
<h1 id="haha"></h1>
</body>
</html>