PocketMine-MP 5.21.2 git-a6534ecbbbcf369264567d27e5ed70f7f5be9816
Loading...
Searching...
No Matches
ServerSocket.php
1<?php
2
3/*
4 * This file is part of RakLib.
5 * Copyright (C) 2014-2022 PocketMine Team <https://github.com/pmmp/RakLib>
6 *
7 * RakLib is not affiliated with Jenkins Software LLC nor RakNet.
8 *
9 * RakLib is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
13 */
14
15declare(strict_types=1);
16
17namespace raklib\server;
18
22use function socket_bind;
23use function socket_last_error;
24use function socket_recvfrom;
25use function socket_sendto;
26use function socket_set_option;
27use function socket_strerror;
28use function strlen;
29use function trim;
30
31class ServerSocket extends Socket{
32
33 public function __construct(
34 private InternetAddress $bindAddress
35 ){
36 parent::__construct($this->bindAddress->getVersion() === 6);
37
38 if(@socket_bind($this->socket, $this->bindAddress->getIp(), $this->bindAddress->getPort()) === true){
39 $this->setSendBuffer(1024 * 1024 * 8)->setRecvBuffer(1024 * 1024 * 8);
40 }else{
41 $error = socket_last_error($this->socket);
42 if($error === SOCKET_EADDRINUSE){ //platform error messages aren't consistent
43 throw new SocketException("Failed to bind socket: Something else is already running on $this->bindAddress", $error);
44 }
45 throw new SocketException("Failed to bind to " . $this->bindAddress . ": " . trim(socket_strerror($error)), $error);
46 }
47 }
48
49 public function getBindAddress() : InternetAddress{
50 return $this->bindAddress;
51 }
52
53 public function enableBroadcast() : bool{
54 return socket_set_option($this->socket, SOL_SOCKET, SO_BROADCAST, 1);
55 }
56
57 public function disableBroadcast() : bool{
58 return socket_set_option($this->socket, SOL_SOCKET, SO_BROADCAST, 0);
59 }
60
67 public function readPacket(?string &$source, ?int &$port) : ?string{
68 $buffer = "";
69 if(@socket_recvfrom($this->socket, $buffer, 65535, 0, $source, $port) === false){
70 $errno = socket_last_error($this->socket);
71 if($errno === SOCKET_EWOULDBLOCK){
72 return null;
73 }
74 throw new SocketException("Failed to recv (errno $errno): " . trim(socket_strerror($errno)), $errno);
75 }
76 return $buffer;
77 }
78
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);
87 }
88 return $result;
89 }
90}
setSendBuffer(int $size)
Definition Socket.php:69
readPacket(?string &$source, ?int &$port)
writePacket(string $buffer, string $dest, int $port)