forked from hy0kl/event-json-rpc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket-client.php
More file actions
executable file
·96 lines (80 loc) · 2.2 KB
/
socket-client.php
File metadata and controls
executable file
·96 lines (80 loc) · 2.2 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env php
<?php
/**
* @describe:
* @author: Jerry Yang(hy0kle@gmail.com)
* */
error_reporting(E_ALL);
set_time_limit(0);
echo "<h2>TCP/IP Connection</h2>\n";
$port = 5555;
$ip = "127.0.0.1";
/*
+-------------------------------
* @socket连接整个过程
+-------------------------------
* @socket_create
* @socket_connect
* @socket_write
* @socket_read
* @socket_close
+--------------------------------
*/
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (! $socket) {
echo "socket_create() failed: reason: " . socket_strerror($socket) . PHP_EOL;
exit;
}else {
echo "socket_create() OK.\n";
}
echo "试图连接 '$ip' 端口 '$port'...\n";
$result = socket_connect($socket, $ip, $port);
if (! $result) {
$err = socket_last_error($socket);
echo "socket_connect() failed.\nReason: ($err) " . socket_strerror($err) . PHP_EOL;
exit;
}else {
echo "连接OK\n";
}
$cmd = 1221;
if ($argc > 1) {
$cmd = $argv[1] + 0;
}
$input = array(
'cmd' => $cmd,
'data' => array(
'test' => 'abc',
'mt_rand' => mt_rand(),
'name' => 'tester',
'timestamp' => time(),
'microsecond' => microtime(true),
),
);
$input_json = json_encode($input);
$body_len = strlen($input_json);
$req = pack('i', $body_len) . $input_json;
echo '@' . strlen($req) . '@' . PHP_EOL;
if (! socket_write($socket, $req, 4 + $body_len)) {
$err = socket_last_error($socket);
echo "socket_write() failed: reason: " . socket_strerror($err) . PHP_EOL;
} else {
echo "发送到服务器信息成功![req: {$input_json}] [req len: {$body_len}]" . PHP_EOL;
}
echo '---------------' . PHP_EOL;
$buf = socket_read($socket, 4);
$body_data = array_merge(unpack('i', $buf));
$body_len = $body_data[0];
if ($body_len > 0) {
echo sprintf('body_len: %d', $body_len) . PHP_EOL;
$buf = socket_read($socket, $body_len);
echo $buf . PHP_EOL;
}
echo '---------------' . PHP_EOL;
// while($out = socket_read($socket, 8192)) {
// echo "接收服务器回传信息成功!\n";
// echo "接受的内容为:",$out;
// }
echo "关闭SOCKET...\n";
socket_close($socket);
echo "关闭OK\n";
/* vi:set ts=4 sw=4 et fdm=marker: */