Creating a TCP Server with Swoole in PHP

This article demonstrates how to build a high‑performance asynchronous TCP server using the Swoole extension in PHP, covering server creation, event callbacks for connection, data reception, and closure, as well as testing the server with telnet or netcat.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Creating a TCP Server with Swoole in PHP

Swoole\Server is a PHP extension for creating high‑performance TCP servers that support both TCP and Unix socket connections.

The article provides a complete example in a file tcp_server.php, showing how to instantiate the server, register event callbacks for onConnect, onReceive, and onClose, and start listening on 127.0.0.1:9506.

In the onConnect callback the server acknowledges a new client; the onReceive callback echoes back the received data prefixed with “Server: ”; the onClose callback logs when a client disconnects.

After running the script, you can verify the listening port with netstat and test the server using telnet or netcat, sending a “hello” message and receiving the echoed response.

The guide also notes that the server can handle thousands of simultaneous connections, each identified by a unique file descriptor ($fd).

Full example code:

<?php
// 创建 Server 对象,监听 127.0.0.1:9506 端口
$serv = new Swoole\Server("127.0.0.1", 9506);

// 监听连接进入事件
$serv->on('Connect', function ($serv, $fd) {
    echo "Client: Connect.
";
});

// 监听数据接收事件
$serv->on('Receive', function ($serv, $fd, $from_id, $data) {
    $serv->send($fd, "Server: " . $data);
});

// 监听连接关闭事件
$serv->on('Close', function ($serv, $fd) {
    echo "Client: Close.
";
});

// 启动服务器
$serv->start();
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendTCPPHPServerAsyncSwoole
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.