您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
workerman直接使用TCP传输数据
发布时间:2021-11-27 16:15:14编辑:雪饮阅读()
创建start.php:
<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
// 创建一个Worker监听2347端口,不使用任何应用层协议
$tcp_worker = new Worker("tcp://0.0.0.0:2347");
// 启动4个进程对外提供服务
$tcp_worker->count = 4;
// 当客户端发来数据时
$tcp_worker->onMessage = function(TcpConnection $connection, $data)
{
// 向客户端发送hello $data
$connection->send('hello ' . $data);
};
// 运行worker
Worker::runAll();
开启该tcp服务端:
[root@localhost workerman]# php -c /usr/local/php734/lib/php/php.ini start.php start
Workerman[start.php] start in DEBUG mode
---------------------------------------- WORKERMAN -----------------------------------------
Workerman version:4.0.22 PHP version:7.3.4
----------------------------------------- WORKERS ------------------------------------------
proto user worker listen processes status
tcp root none tcp://0.0.0.0:2347 4 [OK]
--------------------------------------------------------------------------------------------
Press Ctrl+C to stop. Start success.
用telnet给服务端发送tcp消息:
[root@localhost ~]# telnet 127.0.0.1 2347
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
tom
hello tom
jack
hello jack
kasumi
hello kasumi
个人认为裸tcp协议聊天的性能比websocket聊天的性能更好。
注意,进入telnet后如果需要退出:
ctrl+],然后再按q就可以了。
这里以linux环境为例,windows环境下可能有所不同。
关键字词:workerman,TCP