1.在/web/tool/demo/server下新建tcp.php
```
<?php
//创建Server对象,监听 127.0.0.1:9501端口
$serv = new swoole_server("127.0.0.1", 9501);
$serv->set([
'worker_num' => 4 , // worker进程数 cpu 1-4,ps aft|grep tcp.php验证是否开启
'max_request' => 10000,
]);
//监听连接进入事件
/**
* $fd 客户端连接的唯一标示
* $reactor_id 线程id
*/
$serv->on('connect', function ($serv, $fd, $reactor_id) {
echo "Client: {$reactor_id} - {$fd}-Connect.\n";
});
//监听数据接收事件
$serv->on('receive', function ($serv, $fd, $reactor_id, $data) {
$serv->send($fd, "Server: {$reactor_id} - {$fd}".$data);
});
//监听连接关闭事件
$serv->on('close', function ($serv, $fd) {
echo "Client: Close.\n";
});
//启动服务器
$serv->start();
```
2.启动服务
```
cd /web/tool/demo/server
php tcp.php
```
![](https://img.kancloud.cn/48/6d/486d4f4deb75a602fea150dcf76d77c5_390x48.png)
3.新建终端查看端口9501
```
netstat -anp | grep 9501
补充
关掉端口
kill 1328
```
![](https://img.kancloud.cn/1e/75/1e756134332cea8bca31308bbee6a2c3_645x69.png)
4.新建终端连接9501
```
telnet 127.0.0.1 9501
```
可以看到响应如下
![](https://img.kancloud.cn/27/93/2793855ba321d3de4faf5843505c73b6_360x85.png)
![](https://img.kancloud.cn/a5/e7/a5e77170696689e142a947cbd0f20ce2_383x109.png)
再开启一个终端测试
![](https://img.kancloud.cn/48/52/485240ecd2982dc8148b5c749b8b453d_672x142.png)