PocketMine-MP 5.21.2 git-b2aa6396c3cc2cafdd815eacc360e1ad89599899
Loading...
Searching...
No Matches
Socket.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\generic;
18
19use function socket_close;
20use function socket_create;
21use function socket_last_error;
22use function socket_set_block;
23use function socket_set_nonblock;
24use function socket_set_option;
25use function socket_strerror;
26use function trim;
27use const AF_INET;
28use const AF_INET6;
29use const IPV6_V6ONLY;
30use const SO_RCVBUF;
31use const SO_SNDBUF;
32use const SOCK_DGRAM;
33use const SOL_SOCKET;
34use const SOL_UDP;
35
36abstract class Socket{
37 protected \Socket $socket;
38
42 protected function __construct(bool $ipv6){
43 $socket = @socket_create($ipv6 ? AF_INET6 : AF_INET, SOCK_DGRAM, SOL_UDP);
44 if($socket === false){
45 throw new \RuntimeException("Failed to create socket: " . trim(socket_strerror(socket_last_error())));
46 }
47 $this->socket = $socket;
48
49 if($ipv6){
50 socket_set_option($this->socket, IPPROTO_IPV6, IPV6_V6ONLY, 1); //Don't map IPv4 to IPv6, the implementation can create another RakLib instance to handle IPv4
51 }
52 }
53
54 public function getSocket() : \Socket{
55 return $this->socket;
56 }
57
58 public function close() : void{
59 socket_close($this->socket);
60 }
61
62 public function getLastError() : int{
63 return socket_last_error($this->socket);
64 }
65
69 public function setSendBuffer(int $size){
70 @socket_set_option($this->socket, SOL_SOCKET, SO_SNDBUF, $size);
71
72 return $this;
73 }
74
78 public function setRecvBuffer(int $size){
79 @socket_set_option($this->socket, SOL_SOCKET, SO_RCVBUF, $size);
80
81 return $this;
82 }
83
87 public function setRecvTimeout(int $seconds, int $microseconds = 0){
88 @socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, ["sec" => $seconds, "usec" => $microseconds]);
89
90 return $this;
91 }
92
93 public function setBlocking(bool $blocking) : void{
94 if($blocking){
95 socket_set_block($this->socket);
96 }else{
97 socket_set_nonblock($this->socket);
98 }
99 }
100}
setSendBuffer(int $size)
Definition Socket.php:69
setRecvBuffer(int $size)
Definition Socket.php:78
setRecvTimeout(int $seconds, int $microseconds=0)
Definition Socket.php:87
__construct(bool $ipv6)
Definition Socket.php:42