33 public function __construct(
36 parent::__construct($this->bindAddress->getVersion() === 6);
38 if(@socket_bind($this->socket, $this->bindAddress->getIp(), $this->bindAddress->getPort()) ===
true){
39 $this->
setSendBuffer(1024 * 1024 * 8)->setRecvBuffer(1024 * 1024 * 8);
41 $error = socket_last_error($this->socket);
42 if($error === SOCKET_EADDRINUSE){
43 throw new SocketException(
"Failed to bind socket: Something else is already running on $this->bindAddress", $error);
45 throw new SocketException(
"Failed to bind to " . $this->bindAddress .
": " . trim(socket_strerror($error)), $error);
50 return $this->bindAddress;
53 public function enableBroadcast() :
bool{
54 return socket_set_option($this->socket, SOL_SOCKET, SO_BROADCAST, 1);
57 public function disableBroadcast() :
bool{
58 return socket_set_option($this->socket, SOL_SOCKET, SO_BROADCAST, 0);
67 public function readPacket(?
string &$source, ?
int &$port) : ?string{
69 if(@socket_recvfrom($this->socket, $buffer, 65535, 0, $source, $port) ===
false){
70 $errno = socket_last_error($this->socket);
71 if($errno === SOCKET_EWOULDBLOCK){
74 throw new SocketException(
"Failed to recv (errno $errno): " . trim(socket_strerror($errno)), $errno);
82 public function writePacket(
string $buffer,
string $dest,
int $port) : int{
83 $result = @socket_sendto($this->socket, $buffer, strlen($buffer), 0, $dest, $port);
84 if($result ===
false){
85 $errno = socket_last_error($this->socket);
86 throw new SocketException(
"Failed to send to $dest $port (errno $errno): " . trim(socket_strerror($errno)), $errno);