1. Go to this page and download the library: Download wp-breeder/swoft-socket library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
namespace SwoftTest\Socket\Testing\Listeners;
use Swoft\Bootstrap\Listeners\Interfaces\CloseInterface;
use Swoft\Bootstrap\Listeners\Interfaces\ConnectInterface;
use Swoft\Bootstrap\Listeners\Interfaces\ReceiveInterface;
use Swoft\Socket\Bean\Annotation\SocketListener;
use Swoft\Socket\Event\SwooleEvent;
use Swoole\Server;
/**
* tcp 监听 demo
* Class SocketListenerTest
* @package SwoftTest\Socket\Testing\Listeners
* @SocketListener({
* SwooleEvent::ON_CONNECT,
* SwooleEvent::ON_RECEIVE,
* SwooleEvent::ON_CLOSE,
* },
* name="tcp"
* )
*/
class TcpListener implements ReceiveInterface, CloseInterface, ConnectInterface
{
public function onConnect(Server $server, int $fd, int $reactorId)
{
echo "tcp connect" . PHP_EOL;
}
public function onReceive(Server $server, int $fd, int $reactorId, string $data)
{
echo "tcp receive data: " . $data . PHP_EOL;
}
public function onClose(Server $server, int $fd, int $reactorId)
{
echo "tcp close" . PHP_EOL;
}
}
namespace SwoftTest\Socket\Testing\Listeners;
use Swoft\Socket\Event\SwooleEvent;
use Swoft\Bootstrap\Listeners\Interfaces\PacketInterface;
use Swoft\Socket\Bean\Annotation\SocketListener;
use Swoole\Server;
/**
* udp 监听 demo
* Class PacketListener
* @package SwoftTest\Socket\Testing\Listeners
* @SocketListener(event={SwooleEvent::ON_PACKET}, name="udp")
*/
class PacketListener implements PacketInterface
{
public function onPacket(Server $server, string $data, array $clientInfo)
{
echo "udp receive data: " . $data;
}
}
shell
php bin/swoft socket:start
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.