-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket.php
More file actions
76 lines (67 loc) · 2.41 KB
/
websocket.php
File metadata and controls
76 lines (67 loc) · 2.41 KB
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
<?php
use Swoole\WebSocket\Server;
class WebSocketServer
{
const int COLS = 80;
const int ROWS = 24;
public Server $server;
private array $instance = [];
public function __construct()
{
$this->server = new Swoole\WebSocket\Server("0.0.0.0", 9502);
$this->server->on('open', function (Swoole\WebSocket\Server $server, Swoole\Http\Request $request) {
$fd = $request->fd;
$fp = $this->connectionServer(true);
echo "server: handshake success with fd{$fd}\n";
//连接服务器
$this->instance[$fd] = $fp;
//数据后端到前端
Swoole\Event::add($fp, function ($fp) use ($server, $fd) {
$data = fread($fp, 8192);
$server->push($fd, mb_convert_encoding($data, "UTF-8"));
});
});
$this->server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
//数据前端到后端
$data = json_decode($frame->data, true);
if ($data) {
switch ($data['type']) {
case 'data':
fwrite($this->instance[$frame->fd], $data['data']);
break;
case 'resize':
if (function_exists('ssh2_shell_resize')) {
ssh2_shell_resize($this->instance[$frame->fd], $data['resize']['cols'], $data['resize']['rows']);
}
break;
}
}
});
$this->server->on('close', function ($ser, $fd) {
echo "client {$fd} closed\n";
$fp = $this->instance[$fd];
Swoole\Event::del($fp);
fclose($fp);
unset($this->instance[$fd]);
});
}
private function connectionServer($userKey = true)
{
$connection = ssh2_connect('127.0.0.1');
if ($userKey) {
$auth = ssh2_auth_pubkey_file($connection, 'root', 'pub', 'key', '123456');
} else {
$auth = ssh2_auth_password($connection, 'root', '123456');
}
if ($auth) {
return ssh2_shell($connection, 'xterm', null, self::COLS, self::ROWS, SSH2_TERM_UNIT_CHARS);
}
throw new Exception('认证失败');
}
public function run(): void
{
$this->server->start();
}
}
$server = new WebSocketServer();
$server->run();