analogic/socket
Analogic Socket is a PHP package for building lightweight TCP/UDP socket clients and servers. It provides simple APIs for connecting, sending/receiving data, and handling basic networking workflows without pulling in a full framework.
Installation
composer require analogic/socket
vendor/analogic/socket exists in your project.Basic Usage
Create a socket client/server in routes/web.php or a dedicated controller:
use Analogic\Socket\Socket;
// Client example (connect to a server)
$socket = new Socket('tcp://127.0.0.1:9000');
$socket->connect();
$socket->write("Hello Server!");
echo $socket->read(); // Output server response
$socket->close();
// Server example (listen for connections)
$server = new Socket('tcp://127.0.0.1:9000');
$server->bind();
$server->listen();
$client = $server->accept();
echo $client->read(); // Output "Hello Server!"
$client->write("Hello Client!");
$client->close();
$server->close();
First Use Case
fsockopen calls with this wrapper for consistency.Connection Management
$socketManager = new \App\Services\SocketManager();
$socket = $socketManager->getSocket('tcp://api.example.com:8080');
connect() or read():
$socket->setTimeout(5); // 5 seconds
Data Handling
write() for raw data or writeLine() for newline-delimited messages.read() until no data remains:
while ($data = $socket->read(1024)) {
processChunk($data);
}
Integration with Laravel
dispatch(new ProcessSocketData($socket, $data));
public function handle($request, Closure $next) {
$response = $socket->read();
if (!$this->validateResponse($response)) {
abort(400);
}
return $next($request);
}
UDP Support
$socket = new Socket('udp://239.255.255.250:1900');
$socket->write("Discovery Packet");
Blocking Calls
read() and accept() are blocking. Use non-blocking mode for async:
$socket->setBlocking(false);
// Check socket status with `select()` or `stream_select()`.
Resource Leaks
close() to free resources. Use a finally block:
try {
$socket->connect();
// ...
} finally {
$socket->close();
}
Error Handling
feof($socket) or socket_last_error() (if using underlying stream).try-catch for SocketException.Deprecated Features
react/socket for async.Stream facade for simple cases.Logging
$data = $socket->read();
\Log::debug("Socket data: " . bin2hex($data));
Testing
netcat (nc) for manual testing:
# Server
nc -l 9000
# Client
nc 127.0.0.1 9000
Configuration Quirks
lsof -i :9000).sudo ufw allow 9000).Custom Protocols
Socket class to add protocol-specific logic:
class CustomSocket extends Socket {
public function sendCommand($command) {
$this->writeLine(json_encode($command));
return json_decode($this->readLine(), true);
}
}
Event-Driven Design
event(new SocketDataReceived($socket, $data));
Dependency Injection
Socket class to Laravel’s container for testing:
$this->app->bind(Socket::class, function () {
return new Socket('tcp://config.sock');
});
How can I help you explore Laravel packages today?