Weave 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 Raw Laravel Package

clue/socket-raw

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require clue/socket-raw
    

    Ensure ext-sockets is enabled in your php.ini (extension=sockets).

  2. Basic Usage

    use Clue\React\Socket\Raw\Connector;
    use React\EventLoop\Factory;
    
    $loop = Factory::create();
    $connector = new Connector($loop);
    
    $connector->connect('tcp://127.0.0.1:8080')->then(
        function ($socket) {
            $socket->write('Hello, Server!');
            $socket->on('data', function ($data) {
                echo "Received: " . $data . "\n";
            });
        }
    );
    
    $loop->run();
    
  3. First Use Case

    • TCP Client: Connect to a raw TCP server (e.g., Redis, custom services).
    • UDP Client: Send/receive datagrams (e.g., DNS queries, IoT devices).

Implementation Patterns

Core Workflows

  1. TCP Client/Server

    // Client
    $connector->connect('tcp://example.com:1234')->then(function ($socket) {
        $socket->write('PING');
    });
    
    // Server
    $server = new Server($loop);
    $server->listen('tcp://0.0.0.0:1234');
    $server->on('connection', function ($socket) {
        $socket->on('data', function ($data) use ($socket) {
            $socket->write('ACK: ' . $data);
        });
    });
    
  2. UDP Client/Server

    // Client
    $udpSocket = new Socket($loop, AF_INET, SOCK_DGRAM, SOL_UDP);
    $udpSocket->send('UDP PING', '127.0.0.1', 5000);
    
    // Server
    $udpSocket->on('message', function ($data, $address) {
        echo "UDP from {$address}: " . $data . "\n";
    });
    
  3. Integration with ReactPHP

    • Use Clue\React\Socket\Raw\Connector/Server with ReactPHP’s event loop for async I/O.
    • Example: Combine with React\Socket\ConnectionInterface for higher-level protocols (e.g., HTTP).
  4. Binary Data Handling

    $socket->on('data', function ($binaryData) {
        $unpacked = unpack('C*', $binaryData); // Convert binary to array
        // Process binary protocol (e.g., Redis, custom binary formats)
    });
    

Common Patterns

  • Timeouts: Use $socket->setTimeout(5.0) to avoid hanging.
  • Error Handling: Attach to error event:
    $socket->on('error', function ($error) {
        echo "Socket error: " . $error->getMessage() . "\n";
    });
    
  • Reusable Connections: Pool sockets for high-performance scenarios (e.g., game servers).

Gotchas and Tips

Pitfalls

  1. Blocking Calls

    • Avoid synchronous socket_* functions; always use async methods (e.g., write(), send()).
    • Fix: Ensure all socket operations are event-driven.
  2. Resource Leaks

    • Unbind/listen sockets explicitly when done:
      $server->close();
      $socket->close();
      
    • Fix: Use finally or React\Promise\Timer\timeout() to ensure cleanup.
  3. Protocol Mismatches

    • Raw sockets don’t handle framing (e.g., HTTP headers). Use libraries like react/http for higher-level protocols.
    • Fix: Implement custom framing logic if needed (e.g., length-prefixed messages).
  4. IPv6/Unix Domain Sockets

    • IPv6 requires AF_INET6; Unix sockets use AF_UNIX:
      $socket = new Socket($loop, AF_UNIX, SOCK_STREAM);
      $socket->connect('/tmp/mysocket.sock');
      

Debugging Tips

  • Enable Socket Debugging:
    $socket->on('debug', function ($message) {
        error_log($message);
    });
    
  • Check Socket State:
    if ($socket->isWritable()) {
        $socket->write('Data');
    }
    
  • Use strace/tcpdump:
    • For low-level debugging, trace system calls or network traffic:
      strace -f -e trace=network php your_script.php
      

Extension Points

  1. Custom Protocols

    • Extend Clue\React\Socket\Raw\Socket to add protocol-specific logic (e.g., encryption, compression).
  2. ReactPHP Integration

    • Combine with React\Promise for chaining:
      $connector->connect('tcp://...')->then(function ($socket) {
          return $socket->write('Data')->then(function () use ($socket) {
              $socket->close();
          });
      });
      
  3. Laravel Integration

    • Use with Laravel’s event loop (e.g., spatie/react package) for async tasks:
      use Spatie\Async\Async;
      
      Async::onLoop(function () {
          $loop = Factory::create();
          // Socket logic here
          $loop->run();
      });
      
  4. Performance Tuning

    • Adjust buffer sizes or use socket_set_nonblock() for high-throughput scenarios.
    • Tip: For UDP, batch messages to reduce system calls.
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.
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels