forked from RetroAchievements/RAWeb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho_client2.php
More file actions
100 lines (80 loc) · 2.03 KB
/
echo_client2.php
File metadata and controls
100 lines (80 loc) · 2.03 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
96
97
98
99
100
<pre><?php
//header( 'Content-type: text/html; charset=utf-8' );
set_time_limit( 60 * 5 ); // ( 60 * 60 * 24 );
ob_implicit_flush( TRUE );
define('SOCK_MSG_DELIM',"_*_");
$myUID = 51;
$maxDuration = 30.0;
function echoAndFlush( $str )
{
echo $str . "\n";
ob_flush();
}
function FormatSocketMessage( $type, $myUID, $content )
{
return "$type,$myUID,$content" . SOCK_MSG_DELIM;
}
function SocketWrite( $connection, $type, $msg = '' )
{
$socketName = stream_socket_get_name( $connection, TRUE );
$msgData = "$type,0,$msg";
//echoAndFlush( "[ SND to $socketName ]:$msgData" );
fputs( $connection, $msgData . SOCK_MSG_DELIM );
}
function SplitPacket( $packetData, &$msgType, &$msgUID, &$msgData )
{
//echoAndFlush( $packetData );
$splitData = explode( ',', $packetData );
$msgType = $splitData[0]; // Type
$msgUID = $splitData[1]; // UID
$msgData = $splitData[2]; // Data (concat tbd?)
}
$i = 15;
$conn = stream_socket_client( "tcp://127.0.0.1:45456", $errno, $errstr );
echoAndFlush( "Connected to: " . stream_socket_get_name( $conn, TRUE ) . " as " . stream_socket_get_name( $conn, FALSE ) );
echoAndFlush( "I am UID $myUID" );
SocketWrite( $conn, "HELO", $myUID );
$start = microtime( true );
$end = $start + $maxDuration;
$lastPingSent = 0.0;
do
{
$now = microtime( true );
if( ( $now - $lastPingSent ) > 1.0 )
{
SocketWrite( $conn, "PING" );
$lastPingSent = $now;
}
// Test sending a msg:
if( $i++ % 18 == 0 )
{
SocketWrite( $conn, "MSG", "Time is $now" );
}
stream_set_blocking( $conn, 0 );
$msg = fread( $conn, 1024 );
$msgsToParse = explode( SOCK_MSG_DELIM, $msg );
foreach( $msgsToParse as $nextMessage )
{
if( strlen( $nextMessage ) < 2 )
continue;
SplitPacket( $nextMessage, $msgType, $msgUID, $msgData );
if( strncmp( $msgType, 'PONG', 4 ) == 0 )
{
// Ignore!
}
else if( strncmp( $msgType, 'MSG', 3 ) == 0 )
{
// Ignore!
echoAndFlush( $msgData );
}
else
{
// Ignore?
}
}
usleep( 70000 ); // 0.1s
}
while( $now < $end );
fclose( $conn );
echoAndFlush( "end!" );
?></pre>