ILIAS  release_5-2 Revision v5.2.25-18-g3f80b82851
UdpSocket.php
Go to the documentation of this file.
1 <?php
2 
3 /*
4  * This file is part of the Monolog package.
5  *
6  * (c) Jordi Boggiano <j.boggiano@seld.be>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11 
13 
14 class UdpSocket
15 {
16  const DATAGRAM_MAX_LENGTH = 65023;
17 
18  protected $ip;
19  protected $port;
20  protected $socket;
21 
22  public function __construct($ip, $port = 514)
23  {
24  $this->ip = $ip;
25  $this->port = $port;
26  $this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
27  }
28 
29  public function write($line, $header = "")
30  {
31  $this->send($this->assembleMessage($line, $header));
32  }
33 
34  public function close()
35  {
36  if (is_resource($this->socket)) {
37  socket_close($this->socket);
38  $this->socket = null;
39  }
40  }
41 
42  protected function send($chunk)
43  {
44  if (!is_resource($this->socket)) {
45  throw new \LogicException('The UdpSocket to '.$this->ip.':'.$this->port.' has been closed and can not be written to anymore');
46  }
47  socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
48  }
49 
50  protected function assembleMessage($line, $header)
51  {
52  $chunkSize = self::DATAGRAM_MAX_LENGTH - strlen($header);
53 
54  return $header . substr($line, 0, $chunkSize);
55  }
56 }
$header