forked from xPaw/PHP-Source-Query
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.php
More file actions
95 lines (78 loc) · 2.13 KB
/
Copy pathSocket.php
File metadata and controls
95 lines (78 loc) · 2.13 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
<?php
/**
* @author Pavel Djundik
*
* @link https://xpaw.me
* @link https://github.com/xPaw/PHP-Source-Query
*
* @license GNU Lesser General Public License, version 2.1
*
* @internal
*/
namespace xPaw\SourceQuery;
use xPaw\SourceQuery\Exception\InvalidPacketException;
use xPaw\SourceQuery\Exception\SocketException;
/**
* Class Socket
*
* @package xPaw\SourceQuery
*
* @uses xPaw\SourceQuery\Exception\InvalidPacketException
* @uses xPaw\SourceQuery\Exception\SocketException
*/
class Socket extends BaseSocket
{
public function Close( ) : void
{
if( is_resource($this->Socket) )
{
fclose( $this->Socket );
$this->Socket = null;
}
}
public function Open( string $Address, int $Port, int $Timeout, int $Engine ) : void
{
$this->Timeout = $Timeout;
$this->Engine = $Engine;
$this->Port = $Port;
$this->Address = $Address;
$Socket = @fsockopen( 'udp://' . $Address, $Port, $ErrNo, $ErrStr, $Timeout );
if( $ErrNo || $Socket === false )
{
throw new SocketException( 'Could not create socket: ' . $ErrStr, SocketException::COULD_NOT_CREATE_SOCKET );
}
$this->Socket = $Socket;
stream_set_timeout( $this->Socket, $Timeout );
stream_set_blocking( $this->Socket, true );
}
public function Write( int $Header, string $String = '' ) : bool
{
$Command = pack( 'ccccca*', 0xFF, 0xFF, 0xFF, 0xFF, $Header, $String );
$Length = strlen( $Command );
return $Length === fwrite( $this->Socket, $Command, $Length );
}
/**
* Reads from socket and returns Buffer.
*
* @throws InvalidPacketException
*
* @return Buffer Buffer
*/
public function Read( int $Length = 1400 ) : Buffer
{
$Buffer = new Buffer( );
$Buffer->Set( fread( $this->Socket, $Length ) );
$this->ReadInternal( $Buffer, $Length, [ $this, 'Sherlock' ] );
return $Buffer;
}
public function Sherlock( Buffer $Buffer, int $Length ) : bool
{
$Data = fread( $this->Socket, $Length );
if( strlen( $Data ) < 4 )
{
return false;
}
$Buffer->Set( $Data );
return $Buffer->GetLong( ) === -2;
}
}