forked from laruence/mpass
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Request.php
102 lines (81 loc) · 2.09 KB
/
Request.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
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
101
102
<?php
/*
----------------------------------------------------
Mpass - Multi-Process Socket Server for PHP
copyright (c) 2010 Laruence
http://www.laruence.com
If you have any questions or comments, please email:
*/
/**
* Mpass_Request is a wrapper for a client socket
* and define the communication protocol
*<code>
* Read:
* while (!$request->eof()) {
* $input .= $request->read($length);
* }
*
* Write:
* $len = $request->write($data);
* //write do not send to client immediately
* //we need call flush after write
* $request->flush();
*</code>
*
* @package Mpass
*/
class Mpass_Request {
/** client name
* eg: 10.23.33.158:3437
*/
public $name = NULL;
private $_socket = NULL;
private $_pos = 0;
public $initialized = FALSE;
public function __construct($client) {
if (!is_resource($client)) {
return;
}
$this->_socket = $client;
$this->name = stream_socket_get_name($client, TRUE);
$this->initialized = TRUE;
}
public function read($length = 1024) {
$data = stream_socket_recvfrom($this->_socket, $length);
$len = strlen($data);
$this->_pos += $len;
return $data;
}
public function peek($length = 1) {
return stream_socket_recvfrom($this->_socket, 1, STREAM_PEEK);
}
/**
* send data to client
*/
public function write($data) {
$data = strval($data);
$length = strlen($data);
if ($length == 0) {
return 0;
}
/* in case of send failed */
$alreay_sent = 0;
while ($alreay_sent < $length) {
if (($send = stream_socket_sendto($this->_socket, substr($data, $alreay_sent))) < 0) {
break;
}
$alreay_sent += $send;
}
return $length;
}
public function name() {
return $this->name;
}
public function __destruct() {
/** in case of unset socket in user script
* we need do this in Server side */
/* stream_socket_shutdown($this->_socket, STREAM_SHUT_RDWR); */
}
}
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */