amphp/socket
Async, non-blocking socket library for AMPHP. Provides client/server abstractions over TCP, UDP, and Unix domain sockets with DNS resolution, retries, connect timeouts, cancellation, and optional TLS encryption. Implements ReadableStream/WritableStream.
Installation
composer require amphp/socket
Ensure your project uses Amp v3 (fiber-based concurrency) and PHP 8.1+.
First Use Case: TCP Client
use Amp\Socket\connect;
$socket = connect('example.com:80');
$socket->write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
$response = $socket->read();
echo $response;
$socket->close();
First Use Case: TCP Server
use Amp\Socket\listen;
$server = listen('127.0.0.1:1337');
while ($client = $server->accept()) {
$client->write("Hello from server!\r\n");
$client->close();
}
Amp\Socket namespace for core functions (connect, listen, connectTls).Amp\Socket\SocketAddress for address parsing (e.g., InternetAddress::fromString()).Amp\Socket\ConnectContext and Amp\Socket\ServerTlsContext for TLS/configuration.use Amp\Socket\ConnectContext;
use Amp\Socket\RetrySocketConnector;
$connector = new RetrySocketConnector(
new Amp\Socket\DnsSocketConnector(),
maxAttempts: 3,
backoffFactor: 1.5
);
$socket = $connector->connect('example.com:80');
use Amp\Socket\bindUdpSocket;
$socket = bindUdpSocket('127.0.0.1:0');
$socket->send('Hello UDP!', '127.0.0.1:1234');
$datagram = $socket->receive();
use Amp\Socket\ClientTlsContext;
$tlsContext = new ClientTlsContext('example.com');
$socket = connectTls('example.com:443', $tlsContext);
use Amp\Socket\ServerTlsContext;
$tlsContext = new ServerTlsContext(
'/path/to/cert.pem',
'/path/to/key.pem'
);
$server = listen('127.0.0.1:443');
while ($client = $server->accept()) {
$client->setupTls($tlsContext);
// Handle encrypted traffic
}
use function Amp\async;
$server = listen('127.0.0.1:1337');
while ($client = $server->accept()) {
async(function () use ($client) {
$client->write("Handled in fiber!\r\n");
$client->close();
});
}
use Amp\Socket\SocketAddress;
$address = SocketAddress\InternetAddress::fromString('192.168.1.1:8080');
if ($address->getType() === SocketAddress\SocketAddressType::Internet()) {
echo "IP: " . $address->getHost();
}
use Amp\Socket\Socks5SocketConnector;
$connector = new Socks5SocketConnector('proxy.example.com:1080');
$socket = $connector->connect('example.com:80');
$server = listen('unix:///tmp/mysocket.sock');
$client = connect('unix:///tmp/mysocket.sock');
TLS Handshake Timing
$socket->setupTls() completes is unencrypted.$socket->setupTls($tlsContext)->then(function () use ($socket) {
$socket->write("Secure data...\r\n");
});
Blocking Operations
read()/write() calls block the fiber.ByteStream\read() with a timeout or async() for non-blocking ops.
$data = ByteStream\read($socket, 1024, 1000); // 1KB or timeout after 1s
DNS Resolution Failures
DnsSocketConnector fails silently on DNS errors.try-catch or use RetrySocketConnector.
try {
$socket = connect('nonexistent.example:80');
} catch (ConnectException $e) {
echo "Connection failed: " . $e->getMessage();
}
Resource Leaks
$socket->close() or $server->close().Amp\Closable interfaces or context managers.
$socket = connect('example.com:80');
try {
// Use socket...
} finally {
$socket->close();
}
UDP Packet Size
PHP 8.3+ Deprecations
stream_context_set_option() is deprecated.amphp/socket@^2.2.4 (includes fixes).Enable Verbose Errors
error_reporting(E_ALL);
ini_set('display_errors', '1');
Log Socket Events
$socket->on('connect', function () {
error_log("Connected!");
});
Use SocketAddress::getAddress()
$address = $socket->getRemoteAddress();
error_log("Client connected from: " . $address->getHost());
Test with telnet/nc
nc -zv 127.0.0.1 1337 # Test server connectivity
Custom Connectors
Extend Amp\Socket\SocketConnector for custom logic (e.g., auth proxies).
class CustomConnector implements SocketConnector {
public function connect(string $address, ConnectContext $context = null): Socket {
// Custom logic...
}
}
TLS Context Customization
Override ServerTlsContext/ClientTlsContext for non-standard certs.
$tlsContext = new ClientTlsContext(
'example.com',
verifyPeer: false,
verifyPeerName: false
);
Protocol Buffers
Combine with amphp/byte-stream for binary protocols.
use Amp\ByteStream\read;
$data = read($socket, 4); // Read 4-byte header
Integration with amphp/http
Use amphp/socket as a low-level transport for custom HTTP clients/servers.
bindUdpSocket(..., 8192))./tmp/socket.sock).How can I help you explore Laravel packages today?