UdpSocket.php 1.4 KB

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