Swoole 快速起步:创建 TCP 服务器

TCP 协议 (Transport Control Protocol) 属于传输层,在经过三次握手后才建立连接,应用层的大多数协议都基于 TCP 协议完成。

 TCP 服务器脚本

1. 创建脚本:server.php

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

// 配置
$serv->set([
    // 守护进程
    "daemonize" => 0,
    // 进程数量,为CPU核数的1-4倍
    "worker_man" => 8,
    // 更多配置:https://wiki.swoole.com/wiki/page/13.html
]);

/**
 * 监听连接进入事件
 * $serv 创建的 Server 对象
 * $fd 是TCP客户端连接的标识符
 * $reactor_id 是来自于哪个reactor线程
 */
$serv->on('Connect', function ($serv, $fd, $reactorId) {
    echo "Client:{$fd} Connect.\n";
});

/**
 * 监听数据接收事件
 * $data,收到的数据内容,可能是文本或者二进制内容
 */
$serv->on('Receive', function ($serv, $fd, $reactorId, $data) {
    // 向客户端发送消息
    $serv->send($fd, "Server: " . $data);
});

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

// 更多监听事件:https://wiki.swoole.com/wiki/page/41.html

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

2. 执行程序:

php73 ./tcp_server.php 

可能遇到报错:(端口被占用

[2019-09-22 16:43:03 @29769.0]    WARNING    swSocket_bind(:434): bind(127.0.0.1:9501) failed, Error: Address already in use[98]
PHP Fatal error:  Uncaught Swoole\Exception: failed to listen server port[127.0.0.1:9501], Error: Address already in use[98] in /var/www/swoole/demo/tcp/tcp_server.php:3

解决:(查看端口 & kill it

[root@atong tcp]# netstat -anp | grep 9501
tcp        0      0 127.0.0.1:9501          0.0.0.0:*               LISTEN      29765/php73         
[root@atong tcp]# kill 29765

3. 另开窗口 用telnet/netcat工具连接:

[root@atong tcp]# telnet 127.0.0.1 9501
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.

 输入内容

hello world ..

立即返回

Server: hello world

发布了46 篇原创文章 · 获赞 42 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Phplayers/article/details/101162085