ReactPHP实现简单的scoket服务器

首先,确保已经安装了 ReactPHP 库:

1
composer require react/react

然后,创建一个 PHP 文件,比如socket_server.php,并添加以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php

require 'vendor/autoload.php';

use React\Socket\Server;
use React\Socket\ConnectionInterface;
use React\EventLoop\Factory as LoopFactory;

// 创建事件循环
$loop = LoopFactory::create();

// 创建TCP服务器
$server = new Server('127.0.0.1:8080', $loop);

// 当有新的连接时
$server->on('connection', function (ConnectionInterface $conn) {
echo "New connection from {$conn->getRemoteAddress()}\n";

// 当接收到数据时
$conn->on('data', function ($data) use ($conn) {
echo "Received data: $data\n";

// 回显数据给客户端
$conn->write("Echo: $data\n");
});

// 当连接关闭时
$conn->on('close', function () use ($conn) {
echo "Connection closed from {$conn->getRemoteAddress()}\n";
});
});

echo "Server running at tcp://127.0.0.1:8080\n";

// 运行事件循环
$loop->run();

这个脚本创建了一个 TCP 服务器,监听在127.0.0.1:8080。当有新的连接时,它会打印出连接的客户端地址,并在接收到数据时回显数据给客户端。当连接关闭时,它会打印出连接关闭的消息。

要运行这个服务器,只需在命令行中执行:

1
php socket_server.php

然后,你可以使用 telnet 或其他 Socket 客户端工具连接到这个服务器,比如:

1
telnet 127.0.0.1 8080

连接成功后,你可以输入一些文本,服务器会回显你输入的内容。