PHP code example of thenlabs / socket-server
1. Go to this page and download the library: Download thenlabs/socket-server 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/ */
thenlabs / socket-server example snippets
/**
* What this program does is accept multiple connections and forward
* each incoming message to the rest of the connections.
*/
ent;
use ThenLabs\SocketServer\SocketServer;
class HubServer extends SocketServer
{
protected $connections = [];
public function onConnection(ConnectionEvent $event): void
{
foreach ($this->connections as $connection) {
$connection->writeLine("New connection.");
}
$this->connections[] = $event->getConnection();
}
public function onData(DataEvent $event): void
{
$data = $event->getData();
switch ($data) {
case 'exit':
$event->getConnection()->close();
break;
case 'stop':
$event->getServer()->stop();
break;
default:
foreach ($this->connections as $connection) {
if ($connection != $event->getConnection()) {
$connection->writeLine($data);
}
}
break;
}
}
public function onDisconnection(DisconnectionEvent $event): void
{
foreach ($this->connections as $id => $connection) {
if ($connection == $event->getConnection()) {
unset($this->connections[$id]);
break;
}
}
}
}
$server = new HubServer(['socket' => $argv[1] ?? 'tcp://127.0.0.1:9000']);
$server->start();