2 /******************************* PHP-P10 v2 *****************************
3 * Copyright (C) 2011 Philipp Kreil (pk910) *
5 * This program is free software: you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation, either version 3 of the License, or *
8 * (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
18 ************************************************************************
20 * Uplink/Client.class.php
22 * This file contains the basic Client Socket.
27 const CLIENT_RECV_MAX_LINES = 20; //maximum Lines to receive within one recv() call
30 private $traffic = array("in" => 0, "out" => 0);
33 public function connect($host, $port, $bind = null, $ssl = false, $blocking = 0) {
35 $options = array('socket' => array('bindto' => $bind.":0"));
38 $context = stream_context_create($options);
39 $sock = stream_socket_client(($ssl ? 'ssl://' : '').$host.':'.$port, $errno, $errstr, 3, STREAM_CLIENT_CONNECT, $context);
41 $this->timeout = $blocking * 1000;
42 stream_set_blocking($sock, false);
43 $this->socket = $sock;
49 public function disconnect() {
50 if($this->socket == null) return;
51 fclose($this->socket);
55 public function connected() {
56 if($this->socket == null) return false;
57 $read = array($this->socket);
60 $n=@stream_select($read, $write, $except, 0);
61 if($n === FALSE || feof($this->socket)) {
62 $this->socket = false;
68 public function recv() {
69 $read = array($this->socket);
72 $n=@stream_select($read, $write, $except, 0, $this->timeout);
73 if($n === FALSE || feof($this->socket)) {
74 $this->socket = false;
78 while(($line = @fgets($this->socket)) != null) {
81 echo"[recv] ".utf8_decode($line)."\n";
82 $this->traffic['in'] += strlen($line);
84 if(count($lines) >= self::CLIENT_RECV_MAX_LINES) break;
92 public function send($line, $newline = "\r\n") {
93 if($this->socket == null) return;
94 echo"[send] ".utf8_decode($line)."\n";
95 $this->traffic['out'] += strlen($line);
96 fwrite($this->socket,$line.$newline);
99 public function getTraffic() {
100 return $this->traffic;