PocketMine-MP 5.21.1 git-e598364f0695495cbe71ddf0b62f134b51091c6e
ClientSocket.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\client;
18
22use function socket_connect;
23use function socket_last_error;
24use function socket_recv;
25use function socket_send;
26use function socket_strerror;
27use function strlen;
28use function trim;
29
30class ClientSocket extends Socket{
31
32 public function __construct(
33 private InternetAddress $connectAddress
34 ){
35 parent::__construct($this->connectAddress->getVersion() === 6);
36
37 if(!@socket_connect($this->socket, $this->connectAddress->getIp(), $this->connectAddress->getPort())){
38 $error = socket_last_error($this->socket);
39 throw new SocketException("Failed to connect to " . $this->connectAddress . ": " . trim(socket_strerror($error)), $error);
40 }
41 //TODO: is an 8 MB buffer really appropriate for a client??
42 $this->setSendBuffer(1024 * 1024 * 8)->setRecvBuffer(1024 * 1024 * 8);
43 }
44
45 public function getConnectAddress() : InternetAddress{
46 return $this->connectAddress;
47 }
48
52 public function readPacket() : ?string{
53 $buffer = "";
54 if(@socket_recv($this->socket, $buffer, 65535, 0) === false){
55 $errno = socket_last_error($this->socket);
56 if($errno === SOCKET_EWOULDBLOCK){
57 return null;
58 }
59 throw new SocketException("Failed to recv (errno $errno): " . trim(socket_strerror($errno)), $errno);
60 }
61 return $buffer;
62 }
63
67 public function writePacket(string $buffer) : int{
68 $result = @socket_send($this->socket, $buffer, strlen($buffer), 0);
69 if($result === false){
70 $errno = socket_last_error($this->socket);
71 throw new SocketException("Failed to send packet (errno $errno): " . trim(socket_strerror($errno)), $errno);
72 }
73 return $result;
74 }
75}
writePacket(string $buffer)
setSendBuffer(int $size)
Definition: Socket.php:69