source: branches/dev/data/module/Net/Socket.php @ 8

Revision 8, 15.1 KB checked in by root, 17 years ago (diff)

new import

Line 
1<?php
2//
3// +----------------------------------------------------------------------+
4// | PHP Version 4                                                        |
5// +----------------------------------------------------------------------+
6// | Copyright (c) 1997-2003 The PHP Group                                |
7// +----------------------------------------------------------------------+
8// | This source file is subject to version 2.0 of the PHP license,       |
9// | that is bundled with this package in the file LICENSE, and is        |
10// | available at through the world-wide-web at                           |
11// | http://www.php.net/license/2_02.txt.                                 |
12// | If you did not receive a copy of the PHP license and are unable to   |
13// | obtain it through the world-wide-web, please send a note to          |
14// | license@php.net so we can mail you a copy immediately.               |
15// +----------------------------------------------------------------------+
16// | Authors: Stig Bakken <ssb@php.net>                                   |
17// |          Chuck Hagenbuch <chuck@horde.org>                           |
18// +----------------------------------------------------------------------+
19//
20// $Id: Socket.php 6959 2006-11-13 06:40:52Z kakinaka $
21
22if(!defined('SOCKET_PHP_DIR')) {
23    $SOCKET_PHP_DIR = realpath(dirname( __FILE__));
24    define("SOCKET_PHP_DIR", $SOCKET_PHP_DIR); 
25}
26require_once SOCKET_PHP_DIR. '/../PEAR.php';
27
28define('NET_SOCKET_READ',  1);
29define('NET_SOCKET_WRITE', 2);
30define('NET_SOCKET_ERROR', 3);
31
32/**
33 * Generalized Socket class.
34 *
35 * @version 1.1
36 * @author Stig Bakken <ssb@php.net>
37 * @author Chuck Hagenbuch <chuck@horde.org>
38 */
39class Net_Socket extends PEAR {
40
41    /**
42     * Socket file pointer.
43     * @var resource $fp
44     */
45    var $fp = null;
46
47    /**
48     * Whether the socket is blocking. Defaults to true.
49     * @var boolean $blocking
50     */
51    var $blocking = true;
52
53    /**
54     * Whether the socket is persistent. Defaults to false.
55     * @var boolean $persistent
56     */
57    var $persistent = false;
58
59    /**
60     * The IP address to connect to.
61     * @var string $addr
62     */
63    var $addr = '';
64
65    /**
66     * The port number to connect to.
67     * @var integer $port
68     */
69    var $port = 0;
70
71    /**
72     * Number of seconds to wait on socket connections before assuming
73     * there's no more data. Defaults to no timeout.
74     * @var integer $timeout
75     */
76    var $timeout = false;
77
78    /**
79     * Number of bytes to read at a time in readLine() and
80     * readAll(). Defaults to 2048.
81     * @var integer $lineLength
82     */
83    var $lineLength = 2048;
84
85    /**
86     * Connect to the specified port. If called when the socket is
87     * already connected, it disconnects and connects again.
88     *
89     * @param string  $addr        IP address or host name.
90     * @param integer $port        TCP port number.
91     * @param boolean $persistent  (optional) Whether the connection is
92     *                             persistent (kept open between requests
93     *                             by the web server).
94     * @param integer $timeout     (optional) How long to wait for data.
95     * @param array   $options     See options for stream_context_create.
96     *
97     * @access public
98     *
99     * @return boolean | PEAR_Error  True on success or a PEAR_Error on failure.
100     */
101    function connect($addr, $port = 0, $persistent = null, $timeout = null, $options = null)
102    {
103        if (is_resource($this->fp)) {
104            @fclose($this->fp);
105            $this->fp = null;
106        }
107
108        if (!$addr) {
109            return $this->raiseError('$addr cannot be empty');
110        } elseif (strspn($addr, '.0123456789') == strlen($addr) ||
111                  strstr($addr, '/') !== false) {
112            $this->addr = $addr;
113        } else {
114            $this->addr = @gethostbyname($addr);
115        }
116
117        $this->port = $port % 65536;
118
119        if ($persistent !== null) {
120            $this->persistent = $persistent;
121        }
122
123        if ($timeout !== null) {
124            $this->timeout = $timeout;
125        }
126
127        $openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
128        $errno = 0;
129        $errstr = '';
130        if ($options && function_exists('stream_context_create')) {
131            if ($this->timeout) {
132                $timeout = $this->timeout;
133            } else {
134                $timeout = 0;
135            }
136            $context = stream_context_create($options);
137            $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $timeout, $context);
138        } else {
139            if ($this->timeout) {
140                $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $this->timeout);
141            } else {
142                $fp = @$openfunc($this->addr, $this->port, $errno, $errstr);
143            }
144        }
145
146        if (!$fp) {
147            return $this->raiseError($errstr, $errno);
148        }
149
150        $this->fp = $fp;
151
152        return $this->setBlocking($this->blocking);
153    }
154
155    /**
156     * Disconnects from the peer, closes the socket.
157     *
158     * @access public
159     * @return mixed true on success or an error object otherwise
160     */
161    function disconnect()
162    {
163        if (!is_resource($this->fp)) {
164            return $this->raiseError('not connected');
165        }
166
167        @fclose($this->fp);
168        $this->fp = null;
169        return true;
170    }
171
172    /**
173     * Find out if the socket is in blocking mode.
174     *
175     * @access public
176     * @return boolean  The current blocking mode.
177     */
178    function isBlocking()
179    {
180        return $this->blocking;
181    }
182
183    /**
184     * Sets whether the socket connection should be blocking or
185     * not. A read call to a non-blocking socket will return immediately
186     * if there is no data available, whereas it will block until there
187     * is data for blocking sockets.
188     *
189     * @param boolean $mode  True for blocking sockets, false for nonblocking.
190     * @access public
191     * @return mixed true on success or an error object otherwise
192     */
193    function setBlocking($mode)
194    {
195        if (!is_resource($this->fp)) {
196            return $this->raiseError('not connected');
197        }
198
199        $this->blocking = $mode;
200        socket_set_blocking($this->fp, $this->blocking);
201        return true;
202    }
203
204    /**
205     * Sets the timeout value on socket descriptor,
206     * expressed in the sum of seconds and microseconds
207     *
208     * @param integer $seconds  Seconds.
209     * @param integer $microseconds  Microseconds.
210     * @access public
211     * @return mixed true on success or an error object otherwise
212     */
213    function setTimeout($seconds, $microseconds)
214    {
215        if (!is_resource($this->fp)) {
216            return $this->raiseError('not connected');
217        }
218
219        return socket_set_timeout($this->fp, $seconds, $microseconds);
220    }
221
222    /**
223     * Returns information about an existing socket resource.
224     * Currently returns four entries in the result array:
225     *
226     * <p>
227     * timed_out (bool) - The socket timed out waiting for data<br>
228     * blocked (bool) - The socket was blocked<br>
229     * eof (bool) - Indicates EOF event<br>
230     * unread_bytes (int) - Number of bytes left in the socket buffer<br>
231     * </p>
232     *
233     * @access public
234     * @return mixed Array containing information about existing socket resource or an error object otherwise
235     */
236    function getStatus()
237    {
238        if (!is_resource($this->fp)) {
239            return $this->raiseError('not connected');
240        }
241
242        return socket_get_status($this->fp);
243    }
244
245    /**
246     * Get a specified line of data
247     *
248     * @access public
249     * @return $size bytes of data from the socket, or a PEAR_Error if
250     *         not connected.
251     */
252    function gets($size)
253    {
254        if (!is_resource($this->fp)) {
255            return $this->raiseError('not connected');
256        }
257
258        return @fgets($this->fp, $size);
259    }
260
261    /**
262     * Read a specified amount of data. This is guaranteed to return,
263     * and has the added benefit of getting everything in one fread()
264     * chunk; if you know the size of the data you're getting
265     * beforehand, this is definitely the way to go.
266     *
267     * @param integer $size  The number of bytes to read from the socket.
268     * @access public
269     * @return $size bytes of data from the socket, or a PEAR_Error if
270     *         not connected.
271     */
272    function read($size)
273    {
274        if (!is_resource($this->fp)) {
275            return $this->raiseError('not connected');
276        }
277
278        return @fread($this->fp, $size);
279    }
280
281    /**
282     * Write a specified amount of data.
283     *
284     * @param string  $data       Data to write.
285     * @param integer $blocksize  Amount of data to write at once.
286     *                            NULL means all at once.
287     *
288     * @access public
289     * @return mixed true on success or an error object otherwise
290     */
291    function write($data, $blocksize = null)
292    {
293        if (!is_resource($this->fp)) {
294            return $this->raiseError('not connected');
295        }
296
297        if (is_null($blocksize) && !OS_WINDOWS) {
298            return fwrite($this->fp, $data);
299        } else {
300            if (is_null($blocksize)) {
301                $blocksize = 1024;
302            }
303
304            $pos = 0;
305            $size = strlen($data);
306            while ($pos < $size) {
307                $written = @fwrite($this->fp, substr($data, $pos, $blocksize));
308                if ($written === false) {
309                    return false;
310                }
311                $pos += $written;
312            }
313
314            return $pos;
315        }
316    }
317
318    /**
319     * Write a line of data to the socket, followed by a trailing "\r\n".
320     *
321     * @access public
322     * @return mixed fputs result, or an error
323     */
324    function writeLine($data)
325    {
326        if (!is_resource($this->fp)) {
327            return $this->raiseError('not connected');
328        }
329
330        return fwrite($this->fp, $data . "\r\n");
331    }
332
333    /**
334     * Tests for end-of-file on a socket descriptor.
335     *
336     * @access public
337     * @return bool
338     */
339    function eof()
340    {
341        return (is_resource($this->fp) && feof($this->fp));
342    }
343
344    /**
345     * Reads a byte of data
346     *
347     * @access public
348     * @return 1 byte of data from the socket, or a PEAR_Error if
349     *         not connected.
350     */
351    function readByte()
352    {
353        if (!is_resource($this->fp)) {
354            return $this->raiseError('not connected');
355        }
356
357        return ord(@fread($this->fp, 1));
358    }
359
360    /**
361     * Reads a word of data
362     *
363     * @access public
364     * @return 1 word of data from the socket, or a PEAR_Error if
365     *         not connected.
366     */
367    function readWord()
368    {
369        if (!is_resource($this->fp)) {
370            return $this->raiseError('not connected');
371        }
372
373        $buf = @fread($this->fp, 2);
374        return (ord($buf[0]) + (ord($buf[1]) << 8));
375    }
376
377    /**
378     * Reads an int of data
379     *
380     * @access public
381     * @return integer  1 int of data from the socket, or a PEAR_Error if
382     *                  not connected.
383     */
384    function readInt()
385    {
386        if (!is_resource($this->fp)) {
387            return $this->raiseError('not connected');
388        }
389
390        $buf = @fread($this->fp, 4);
391        return (ord($buf[0]) + (ord($buf[1]) << 8) +
392                (ord($buf[2]) << 16) + (ord($buf[3]) << 24));
393    }
394
395    /**
396     * Reads a zero-terminated string of data
397     *
398     * @access public
399     * @return string, or a PEAR_Error if
400     *         not connected.
401     */
402    function readString()
403    {
404        if (!is_resource($this->fp)) {
405            return $this->raiseError('not connected');
406        }
407
408        $string = '';
409        while (($char = @fread($this->fp, 1)) != "\x00")  {
410            $string .= $char;
411        }
412        return $string;
413    }
414
415    /**
416     * Reads an IP Address and returns it in a dot formated string
417     *
418     * @access public
419     * @return Dot formated string, or a PEAR_Error if
420     *         not connected.
421     */
422    function readIPAddress()
423    {
424        if (!is_resource($this->fp)) {
425            return $this->raiseError('not connected');
426        }
427
428        $buf = @fread($this->fp, 4);
429        return sprintf("%s.%s.%s.%s", ord($buf[0]), ord($buf[1]),
430                       ord($buf[2]), ord($buf[3]));
431    }
432
433    /**
434     * Read until either the end of the socket or a newline, whichever
435     * comes first. Strips the trailing newline from the returned data.
436     *
437     * @access public
438     * @return All available data up to a newline, without that
439     *         newline, or until the end of the socket, or a PEAR_Error if
440     *         not connected.
441     */
442    function readLine()
443    {
444        if (!is_resource($this->fp)) {
445            return $this->raiseError('not connected');
446        }
447
448        $line = '';
449        $timeout = time() + $this->timeout;
450       
451        while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
452            $line .= @fgets($this->fp, $this->lineLength);
453            if (substr($line, -1) == "\n") {
454                return rtrim($line, "\r\n");
455            }
456        }
457
458        return $line;
459    }
460   
461    /**
462     * Read until the socket closes, or until there is no more data in
463     * the inner PHP buffer. If the inner buffer is empty, in blocking
464     * mode we wait for at least 1 byte of data. Therefore, in
465     * blocking mode, if there is no data at all to be read, this
466     * function will never exit (unless the socket is closed on the
467     * remote end).
468     *
469     * @access public
470     *
471     * @return string  All data until the socket closes, or a PEAR_Error if
472     *                 not connected.
473     */
474    function readAll()
475    {
476        if (!is_resource($this->fp)) {
477            return $this->raiseError('not connected');
478        }
479
480        $data = '';
481        while (!feof($this->fp)) {
482            $data .= @fread($this->fp, $this->lineLength);
483        }
484        return $data;
485    }
486
487    /**
488     * Runs the equivalent of the select() system call on the socket
489     * with a timeout specified by tv_sec and tv_usec.
490     *
491     * @param integer $state    Which of read/write/error to check for.
492     * @param integer $tv_sec   Number of seconds for timeout.
493     * @param integer $tv_usec  Number of microseconds for timeout.
494     *
495     * @access public
496     * @return False if select fails, integer describing which of read/write/error
497     *         are ready, or PEAR_Error if not connected.
498     */
499    function select($state, $tv_sec, $tv_usec = 0)
500    {
501        if (!is_resource($this->fp)) {
502            return $this->raiseError('not connected');
503        }
504
505        $read = null;
506        $write = null;
507        $except = null;
508        if ($state & NET_SOCKET_READ) {
509            $read[] = $this->fp;
510        }
511        if ($state & NET_SOCKET_WRITE) {
512            $write[] = $this->fp;
513        }
514        if ($state & NET_SOCKET_ERROR) {
515            $except[] = $this->fp;
516        }
517        if (false === ($sr = stream_select($read, $write, $except, $tv_sec, $tv_usec))) {
518            return false;
519        }
520
521        $result = 0;
522        if (count($read)) {
523            $result |= NET_SOCKET_READ;
524        }
525        if (count($write)) {
526            $result |= NET_SOCKET_WRITE;
527        }
528        if (count($except)) {
529            $result |= NET_SOCKET_ERROR;
530        }
531        return $result;
532    }
533
534}
Note: See TracBrowser for help on using the repository browser.