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 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| <?php
<?php
class SocketUdp{
public $socket;
public $stream;
public $buf;
public $position;
public $connected;
public $ip;
public $data;
public $port;
public $ipv="ipv4"; // ipv4/ipv6
public function __construct($ip, $port, $ipv = NULL) {
$this->ip = $ip;
$this->port = $port;
if(!empty($ipv)){
$this->ipv = $ipv;
}
if(!isset($this->stream)){
$this->create();
$this->connect();
socket_set_block($this->stream);
stream_set_timeout($this->stream, 1);
}
}
public function send($cmd){
$packet=socket_write($this->stream, sprintf($cmd, 0x00));
echo $packet;
}
public function connect() {
$true = socket_connect($this->stream, $this->ip, $this->port);
if (!$true) {
echo 'Socket::connect() connection error :(<br />';
$this->connected==false;
}else{
// echo "Vous etes connecte au port udp!! <br/>";
}
}
public function create() {
if ($this->ipv == 'ipv4') {
$this->stream = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
}else{
$this->stream = socket_create(AF_INET6, SOCK_DGRAM, SOL_UDP);
}
if ($this->stream === false) {
trigger_error('SocketUDP::create init error :(');
}
}
public function read($vars = array(), $req = NULL){
if($this->connected){
$rec=socket_recv($this->stream, $this->buf, 1400, MSG_WAITALL);
$this->position=4;
if($req=='players'){
$data->type=$this->get_byte();
$data->players=$this->get_byte();
if(empty($data->players)){
$data->players=0;
}else{
for($i=1; $i<=$data->players; $i++){
$this->get_byte();
$data->nom[]=$this->get_string();
$data->kill[]=$this->get_long();
$data->temps[]=$this->get_float();
}
}
}
foreach($vars as $k=>$v){
$f="get_".$v;
$data->$k = self::$f();
}
return $data;
}
}
public function get_byte(){
$data = substr($this->buf, $this->position, 1);
$data = unpack('cvalue', $data);
$this->position+=1;
return $data['value'];
}
public function get_long() {
$data = substr($this->buf, $this->position, 4);
$data = unpack('lvalue', $data);
$this->position+=4;
return $data['value'];
}
public function get_string(){
$str = null;
while(($char = $this->get_char()) != chr(0)){
$str .= $char;
}
return $str;
}
public function get_char(){
$char=substr($this->buf, $this->position, 1);
$this->position+=1;
return $char;
}
public function get_short() {
$data = substr($this->buf, $this->position, 2);
$data = unpack('svalue', $data);
$this->position+=2;
return $data['value'];
}
public function get_float() {
$data = substr($this->buf, $this->position, 4);
$data = unpack('fvalue', $data);
$this->position+=4;
return $data['value'];
}
}
?> |
Partager