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

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require analogic/socket
    
    • Verify vendor/analogic/socket exists in your project.
  2. 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();
    
  3. First Use Case

    • Debugging legacy systems: Replace fsockopen calls with this wrapper for consistency.
    • Prototyping: Quickly test TCP/UDP communication without deep socket knowledge.

Implementation Patterns

Common Workflows

  1. Connection Management

    • Reusable clients: Store socket instances in a singleton or service container:
      $socketManager = new \App\Services\SocketManager();
      $socket = $socketManager->getSocket('tcp://api.example.com:8080');
      
    • Timeout handling: Set timeouts during connect() or read():
      $socket->setTimeout(5); // 5 seconds
      
  2. Data Handling

    • Binary vs. Text: Use write() for raw data or writeLine() for newline-delimited messages.
    • Chunked reads: Loop read() until no data remains:
      while ($data = $socket->read(1024)) {
          processChunk($data);
      }
      
  3. Integration with Laravel

    • Queue jobs: Offload long-running socket operations to queues:
      dispatch(new ProcessSocketData($socket, $data));
      
    • Middleware: Validate socket responses in middleware:
      public function handle($request, Closure $next) {
          $response = $socket->read();
          if (!$this->validateResponse($response)) {
              abort(400);
          }
          return $next($request);
      }
      
  4. UDP Support

    • Broadcasting: Send UDP packets to multiple endpoints:
      $socket = new Socket('udp://239.255.255.250:1900');
      $socket->write("Discovery Packet");
      

Gotchas and Tips

Pitfalls

  1. Blocking Calls

    • read() and accept() are blocking. Use non-blocking mode for async:
      $socket->setBlocking(false);
      // Check socket status with `select()` or `stream_select()`.
      
  2. Resource Leaks

    • Always call close() to free resources. Use a finally block:
      try {
          $socket->connect();
          // ...
      } finally {
          $socket->close();
      }
      
  3. Error Handling

    • Check socket status with feof($socket) or socket_last_error() (if using underlying stream).
    • Wrap operations in try-catch for SocketException.
  4. Deprecated Features

    • The package is abandoned (2016). Avoid for production; prefer:
      • react/socket for async.
      • Laravel’s built-in Stream facade for simple cases.

Debugging Tips

  1. Logging

    • Log raw socket data for debugging:
      $data = $socket->read();
      \Log::debug("Socket data: " . bin2hex($data));
      
  2. Testing

    • Use netcat (nc) for manual testing:
      # Server
      nc -l 9000
      # Client
      nc 127.0.0.1 9000
      
  3. Configuration Quirks

    • Port conflicts: Ensure the port isn’t used by another service (e.g., lsof -i :9000).
    • Firewall rules: Allow traffic on the socket’s port (sudo ufw allow 9000).

Extension Points

  1. Custom Protocols

    • Extend the 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);
          }
      }
      
  2. Event-Driven Design

    • Combine with Laravel Events for async workflows:
      event(new SocketDataReceived($socket, $data));
      
  3. Dependency Injection

    • Bind the Socket class to Laravel’s container for testing:
      $this->app->bind(Socket::class, function () {
          return new Socket('tcp://config.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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours