Table of Contents
How to Create a Simple TCP Server Using Workerman?
Can Workerman Handle Multiple TCP Client Connections Concurrently?
What Are the Basic Configuration Settings for a Workerman TCP Server?
How Do I Send and Receive Data Using a Workerman TCP Server?
Home PHP Framework Workerman How do I create a simple TCP server using Workerman?

How do I create a simple TCP server using Workerman?

Mar 11, 2025 pm 02:58 PM

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();
Copy after login

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 ...
Copy after login

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);
};
Copy after login

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!");
};
Copy after login

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 of this Website
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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What Are the Key Features of Workerman's Built-in WebSocket Client? What Are the Key Features of Workerman's Built-in WebSocket Client? Mar 18, 2025 pm 04:20 PM

Workerman's WebSocket client enhances real-time communication with features like asynchronous communication, high performance, scalability, and security, easily integrating with existing systems.

How to Use Workerman for Building Real-Time Collaboration Tools? How to Use Workerman for Building Real-Time Collaboration Tools? Mar 18, 2025 pm 04:15 PM

The article discusses using Workerman, a high-performance PHP server, to build real-time collaboration tools. It covers installation, server setup, real-time feature implementation, and integration with existing systems, emphasizing Workerman's key f

How to Use Workerman for Building Real-Time Analytics Dashboards? How to Use Workerman for Building Real-Time Analytics Dashboards? Mar 18, 2025 pm 04:07 PM

The article discusses using Workerman, a high-performance PHP server, to build real-time analytics dashboards. It covers installation, server setup, data processing, and frontend integration with frameworks like React, Vue.js, and Angular. Key featur

How to Implement Real-Time Data Synchronization with Workerman and MySQL? How to Implement Real-Time Data Synchronization with Workerman and MySQL? Mar 18, 2025 pm 04:13 PM

The article discusses implementing real-time data synchronization using Workerman and MySQL, focusing on setup, best practices, ensuring data consistency, and addressing common challenges.

What Are the Key Considerations for Using Workerman in a Serverless Architecture? What Are the Key Considerations for Using Workerman in a Serverless Architecture? Mar 18, 2025 pm 04:12 PM

The article discusses integrating Workerman into serverless architectures, focusing on scalability, statelessness, cold starts, resource management, and integration complexity. Workerman enhances performance through high concurrency, reduced cold sta

What Are the Advanced Features of Workerman's WebSocket Server? What Are the Advanced Features of Workerman's WebSocket Server? Mar 18, 2025 pm 04:08 PM

Workerman's WebSocket server enhances real-time communication with features like scalability, low latency, and security measures against common threats.

What Are the Best Ways to Optimize Workerman for Low-Latency Applications? What Are the Best Ways to Optimize Workerman for Low-Latency Applications? Mar 18, 2025 pm 04:14 PM

The article discusses optimizing Workerman for low-latency applications, focusing on asynchronous programming, network configuration, resource management, data transfer minimization, load balancing, and regular updates.

How to Implement Custom Middleware in Workerman HTTP Servers? How to Implement Custom Middleware in Workerman HTTP Servers? Mar 18, 2025 pm 04:05 PM

Article discusses implementing custom middleware in Workerman HTTP servers, its benefits, and common issues. Main argument is on enhancing application behavior and performance through middleware.

See all articles