PocketMine-MP/classes/Socket.class.php
Shoghi Cervantes Pueyo c2de8094b2 First commit
2012-10-19 02:21:54 +02:00

98 lines
2.3 KiB
PHP

<?php
/*
-
/ \
/ \
/ POCKET \
/ MINECRAFT PHP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/
class Socket{
private $encrypt;
var $buffer, $connected, $errors, $sock, $server;
function __construct($server, $port, $listen = false, $socket = false){
$this->errors = array_fill(88,(125 - 88) + 1, true);
$this->server = $server;
$this->port = $port;
if($socket !== false){
$this->sock = $socket;
$this->connected = true;
$this->buffer = array();
$this->unblock();
}else{
$this->sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($this->sock, SOL_SOCKET, SO_BROADCAST, 1);
if($listen !== true){
$this->connected = true;
$this->buffer = array();
$this->unblock();
}else{
socket_bind($this->sock, "0.0.0.0", $port);
$this->unblock();
}
}
}
function listenSocket(){
$sock = @socket_accept($this->sock);
if($sock !== false){
$sock = new Socket(false, false, false, $sock);
$sock->unblock();
return $sock;
}
return false;
}
public function close($error = 125){
$this->connected = false;
if($error === false){
console("[ERROR] [Socket] Socket closed, Error: End of Stream");
}else{
console("[ERROR] [Socket] Socket closed, Error $error: ".socket_strerror($error));
}
return @socket_close($this->sock);
}
public function block(){
socket_set_block($this->sock);
}
public function unblock(){
socket_set_nonblock($this->sock);
}
public function read(){
$source = false;
$port = 1;
$len = @socket_recvfrom($this->sock, $buf, 65536, 0, $source, $port);
return array($buf, $source, $port, $len);
}
public function write($data, $dest = false, $port = false){
return @socket_sendto($this->sock, $data, strlen($data), 0, ($dest === false ? $this->server:$dest), ($port === false ? $this->port:$port));
}
}
?>