Created
June 12, 2013 07:20
-
-
Save henrikbjorn/5763411 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Simple SocketServer that runs over the udp protocol. The run method takes a callable | |
* which is called with the data received. | |
* | |
* @package Socket | |
*/ | |
class SocketServer | |
{ | |
protected $hostname; | |
protected $socket; | |
/** | |
* @param string $hostname A hostname like 127.0.0.1:9001 | |
*/ | |
public function __construct(JsonFormatter $formatter, $hostname = '127.0.0.1:9001') | |
{ | |
$this->formatter = $formatter; | |
$this->hostname = $hostname; | |
} | |
/** | |
* @param callable $callback Any valid callable | |
*/ | |
public function run($callback) | |
{ | |
if (false == is_callable($callback)) { | |
throw new \InvalidArgumentException('"' . $callback . '" is not a valid callable.'); | |
} | |
$this->connect(); | |
while (false !== ($data = stream_socket_recvfrom($this->socket, 2048))) { | |
$this->handle($callback, $data); | |
} | |
} | |
/** | |
* @param callable $callback | |
* @param mixed $data | |
*/ | |
protected function handle($callback, $data) | |
{ | |
$data = $this->formatter->format($data); | |
call_user_func($callback, $data); | |
} | |
/** | |
* @throws RuntimeException | |
*/ | |
protected function connect() | |
{ | |
// This is needed as it will emit a warning instead and ruin my whole life! | |
$this->socket = @stream_socket_server('udp://' . $this->hostname, $errno, $error, STREAM_SERVER_BIND); | |
if (!$this->socket) { | |
throw new \RuntimeException('Could not bind to "udp://' . $this->hostname . '".'); | |
} | |
} | |
} | |
class JsonFormatter | |
{ | |
public function format($data) | |
{ | |
return json_decode($data, true); | |
} | |
} | |
(new SocketServer(new JsonFormatter))->run(function ($data) { | |
var_dump($data); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment