search
HomePHP FrameworkWorkermanHow do I create a simple TCP server using Workerman?

This article demonstrates creating a simple TCP server using PHP's Workerman library. It details server setup, concurrent connection handling via Workerman's event-driven architecture, basic configuration options (e.g., worker count, port reuse), an

How do I create a simple TCP server using Workerman?

How to Create a Simple TCP Server Using Workerman?

Creating a simple TCP server with Workerman is straightforward. First, ensure you have Workerman installed. You can typically install it via Composer: composer require workerman/workerman. Then, create a new PHP file (e.g., server.php). The following code establishes a basic TCP server that listens on port 2345:

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

$worker = new Worker("tcp://0.0.0.0:2345");

$worker->onConnect = function($connection) {
    echo "New connection from {$connection->getRemoteIp()}:{$connection->getRemotePort()}\n";
};

$worker->onMessage = function($connection, $data) {
    // Echo the data back to the client
    $connection->send($data);
};

$worker->onClose = function($connection) {
    echo "Connection closed: {$connection->getRemoteIp()}:{$connection->getRemotePort()}\n";
};

Worker::runAll();

This code uses the Workerman\Worker class to create a TCP worker. tcp://0.0.0.0:2345 specifies the listening address and port. The onConnect, onMessage, and onClose callbacks handle connection events, incoming data, and connection closures respectively. Worker::runAll() starts the server. Remember to run this script from your terminal using php server.php.

Can Workerman Handle Multiple TCP Client Connections Concurrently?

Yes, Workerman is designed to handle multiple TCP client connections concurrently. It uses a multi-process or multi-thread model (depending on your configuration) to efficiently manage numerous simultaneous connections. The key to this concurrent handling lies in the event-driven architecture of Workerman. When a connection arrives or data is received, Workerman triggers the corresponding callbacks (onConnect, onMessage, etc.) without blocking other connections. This allows it to handle many clients without performance degradation. The number of concurrent connections it can handle depends on your server's resources (CPU, memory, network bandwidth). You can adjust the number of worker processes to optimize for your specific needs through Workerman's configuration options.

What Are the Basic Configuration Settings for a Workerman TCP Server?

Workerman offers several configuration options to customize your TCP server. These are typically set within the Worker object. Here are some basic settings:

  • worker->count: Specifies the number of worker processes. Increasing this number can improve performance with more clients, but too many processes can overload the system. The default is usually 1.
  • worker->name: Assigns a name to the worker for better identification in logs and monitoring.
  • worker->reusePort: Enables port reuse, allowing multiple servers to listen on the same port. Useful in some scenarios but requires careful consideration.
  • worker->transport: Specifies the transport layer protocol (e.g., 'tcp', 'udp'). The default is 'tcp'.
  • worker->ssl: Enables SSL/TLS encryption. Requires configuring SSL certificates.

You can modify these settings directly within your server.php file before Worker::runAll(). For example:

$worker = new Worker("tcp://0.0.0.0:2345");
$worker->count = 4; // Use 4 worker processes
$worker->name = "MyTCPServer";
// ... other settings ...

How Do I Send and Receive Data Using a Workerman TCP Server?

Sending and receiving data is handled through the $connection object within the onMessage callback. The server receives data through the $data parameter of the onMessage function. To send data back to the client, use the $connection->send() method.

Receiving Data:

The $data parameter in the onMessage callback contains the data received from the client. You can process this data as needed. For example:

$worker->onMessage = function($connection, $data) {
    $receivedData = trim($data); // Remove leading/trailing whitespace
    echo "Received: " . $receivedData . "\n";
    // Process the received data...
    $response = "Server received: " . $receivedData;
    $connection->send($response);
};

Sending Data:

To send data back to the client, use the $connection->send() method:

$worker->onMessage = function($connection, $data) {
    // ... process data ...
    $connection->send("Hello from the server!");
};

Remember to handle potential errors (e.g., connection failures) appropriately within your callbacks. This provides a basic framework for sending and receiving data within your Workerman TCP server. More complex data handling might involve serialization or other data structuring techniques.

The above is the detailed content of How do I create a simple TCP server using Workerman?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool