Swoole入门

本文的示例代码参考swoole/TCPBasic

目录

  • 环境

  • TCPServer

  • TCPClient

  • 测试

环境

pecl install swoole
php -m | grep swoole # 没有任何信息
echo 'extension=swoole.so' >> $(php  -i | grep 'Loaded Configuration File' | awk -F '=>' '{print $2}')
php -m | grep swoole # swoole

TCPServer

vim TCPServer.php
on('connect', function ($server, $fd){
    echo "connection open: {$fd}\n";
});
$server->on('receive', function ($server, $fd, $reactor_id, $data) {
    $server->send($fd, "Swoole: {$data}");
    $server->close($fd);
});
$server->on('close', function ($server, $fd) {
    echo "connection close: {$fd}\n";
});
$server->start();

TCPClient

vim TCPClient.php
on("connect", function($cli) {
    $cli->send("hello world\n");
});
$client->on("receive", function($cli, $data){
    echo "received: {$data}\n";
});
$client->on("error", function($cli){
    echo "connect failed\n";
});
$client->on("close", function($cli){
    echo "connection close\n";
});
$client->connect("127.0.0.1", 9500, 0.5);

测试

php TCPServer.php

php TCPClient.php
  • Server
connection open: 1
connection close: 1
  • Client
received: Swoole: hello world

connection close

参考

  • Swoole

  • 编译安装

你可能感兴趣的:(Swoole入门)