<?PHP
//This class for use UDP socket connect your app
//Power by shadowkun
//Contact Email:shadowkun@tencent.com
class UdpMsg
{
//IP and PORT for connect
private $serverip;
private $serverport;
private $socket = -1;
function __construct($serverip, $serverport)
{
$this->serverip = $serverip;
$this->serverport = $serverport;
}
function __destruct()
{
if(0 <= $this->socket)
{
socket_close($this->socket);
}
}
function close()
{
if(0 <= $this->socket)
{
socket_close($this->socket);
}
}
function connect()
{
if(($this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) < 0)
{
return -1;
}
socket_set_option($this->socket, SOL_socket, SO_RCVTIMEO, array('sec'=>5,'usec'=>0));
if(!socket_connect($this->socket, $this->serverip, $this->serverport))
{
return -2;
}
return 0;
}
function send($sendStream, $len)
{
if($this->socket < 0)
{
return -1;
}
$ret = socket_write($this->socket, $sendStream, $len);
if($ret != $len)
{
return -2;
}
return 0;
}
function recv(&$recvStream, $len)
{
if($this->socket < 0)
{
return -1;
}
$recvStream = socket_read($this->socket, $len, PHP_BINARY_READ);
//echo bin2hex($recvStream);
if(strlen($recvStream) == 0)
{
return -2;
}
return 0;
}
};
?>