diff --git a/README.md b/README.md index b5aa5ba..ac06dbf 100644 --- a/README.md +++ b/README.md @@ -66,3 +66,18 @@ $secureConnector->create('www.google.com', 443)->then(function (React\Stream\Str $loop->run(); ``` + +### Unix domain sockets + +Similarly, the `UnixConnector` class can be used to connect to Unix domain socket (UDS) +paths like this: + +```php +$connector = new React\SocketClient\UnixConnector($loop); + +$connector->create('/tmp/demo.sock')->then(function (React\Stream\Stream $stream) { + $stream->write("HELLO\n"); +}); + +$loop->run(); +``` diff --git a/src/UnixConnector.php b/src/UnixConnector.php new file mode 100644 index 0000000..e12e7ef --- /dev/null +++ b/src/UnixConnector.php @@ -0,0 +1,36 @@ +loop = $loop; + } + + public function create($path, $unusedPort = 0) + { + $resource = @stream_socket_client('unix://' . $path, $errno, $errstr, 1.0); + + if (!$resource) { + return Promise\reject(new RuntimeException('Unable to connect to unix domain socket "' . $path . '": ' . $errstr, $errno)); + } + + return Promise\resolve(new Stream($resource, $this->loop)); + } +} diff --git a/tests/UnixConnectorTest.php b/tests/UnixConnectorTest.php new file mode 100644 index 0000000..4070aed --- /dev/null +++ b/tests/UnixConnectorTest.php @@ -0,0 +1,46 @@ +loop = $this->getMock('React\EventLoop\LoopInterface'); + $this->connector = new UnixConnector($this->loop); + } + + public function testInvalid() + { + $promise = $this->connector->create('google.com', 80); + $promise->then(null, $this->expectCallableOnce()); + } + + public function testValid() + { + // random unix domain socket path + $path = sys_get_temp_dir() . '/test' . uniqid() . '.sock'; + + // temporarily create unix domain socket server to connect to + $server = stream_socket_server('unix://' . $path, $errno, $errstr); + + // skip test if we can not create a test server (Windows etc.) + if (!$server) { + $this->markTestSkipped('Unable to create socket "' . $path . '": ' . $errstr . '(' . $errno .')'); + return; + } + + // tests succeeds if we get notified of successful connection + $promise = $this->connector->create($path, 0); + $promise->then($this->expectCallableOnce()); + + // clean up server + fclose($server); + unlink($path); + } +}