Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Socket Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require amphp/socket
    

    Ensure your project uses Amp v3 (fiber-based concurrency) and PHP 8.1+.

  2. 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();
    
  3. 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();
    }
    

Where to Look First

  • Amp Socket Docs (official documentation).
  • 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.

Implementation Patterns

1. Client-Server Workflows

TCP Client with Retries

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');

UDP Client/Server

use Amp\Socket\bindUdpSocket;

$socket = bindUdpSocket('127.0.0.1:0');
$socket->send('Hello UDP!', '127.0.0.1:1234');
$datagram = $socket->receive();

2. TLS Integration

Client-Side TLS

use Amp\Socket\ClientTlsContext;

$tlsContext = new ClientTlsContext('example.com');
$socket = connectTls('example.com:443', $tlsContext);

Server-Side TLS

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
}

3. Concurrency with Fibers

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();
    });
}

4. Address Handling

use Amp\Socket\SocketAddress;

$address = SocketAddress\InternetAddress::fromString('192.168.1.1:8080');
if ($address->getType() === SocketAddress\SocketAddressType::Internet()) {
    echo "IP: " . $address->getHost();
}

5. SOCKS5 Proxy Support

use Amp\Socket\Socks5SocketConnector;

$connector = new Socks5SocketConnector('proxy.example.com:1080');
$socket = $connector->connect('example.com:80');

6. Unix Domain Sockets

$server = listen('unix:///tmp/mysocket.sock');
$client = connect('unix:///tmp/mysocket.sock');

Gotchas and Tips

Pitfalls

  1. TLS Handshake Timing

    • Gotcha: Data sent before $socket->setupTls() completes is unencrypted.
    • Fix: Ensure TLS is set up before writing/reading data.
      $socket->setupTls($tlsContext)->then(function () use ($socket) {
          $socket->write("Secure data...\r\n");
      });
      
  2. Blocking Operations

    • Gotcha: Long-running read()/write() calls block the fiber.
    • Fix: Use ByteStream\read() with a timeout or async() for non-blocking ops.
      $data = ByteStream\read($socket, 1024, 1000); // 1KB or timeout after 1s
      
  3. DNS Resolution Failures

    • Gotcha: DnsSocketConnector fails silently on DNS errors.
    • Fix: Wrap in a try-catch or use RetrySocketConnector.
      try {
          $socket = connect('nonexistent.example:80');
      } catch (ConnectException $e) {
          echo "Connection failed: " . $e->getMessage();
      }
      
  4. Resource Leaks

    • Gotcha: Forgetting to call $socket->close() or $server->close().
    • Fix: Use Amp\Closable interfaces or context managers.
      $socket = connect('example.com:80');
      try {
          // Use socket...
      } finally {
          $socket->close();
      }
      
  5. UDP Packet Size

    • Gotcha: UDP datagrams > 65,507 bytes are truncated.
    • Fix: Split large messages or use TCP.
  6. PHP 8.3+ Deprecations

    • Gotcha: stream_context_set_option() is deprecated.
    • Fix: Update to amphp/socket@^2.2.4 (includes fixes).

Debugging Tips

  1. Enable Verbose Errors

    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    
  2. Log Socket Events

    $socket->on('connect', function () {
        error_log("Connected!");
    });
    
  3. Use SocketAddress::getAddress()

    $address = $socket->getRemoteAddress();
    error_log("Client connected from: " . $address->getHost());
    
  4. Test with telnet/nc

    nc -zv 127.0.0.1 1337  # Test server connectivity
    

Extension Points

  1. 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...
        }
    }
    
  2. TLS Context Customization Override ServerTlsContext/ClientTlsContext for non-standard certs.

    $tlsContext = new ClientTlsContext(
        'example.com',
        verifyPeer: false,
        verifyPeerName: false
    );
    
  3. Protocol Buffers Combine with amphp/byte-stream for binary protocols.

    use Amp\ByteStream\read;
    
    $data = read($socket, 4); // Read 4-byte header
    
  4. Integration with amphp/http Use amphp/socket as a low-level transport for custom HTTP clients/servers.


Config Quirks

  • Default TLS Version: Now 1.2+ (up from 1.0 in v1).
  • Chunk Size: Configure per-socket (e.g., bindUdpSocket(..., 8192)).
  • Unix Sockets: Paths must be absolute (e.g., /tmp/socket.sock).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi