Created
May 1, 2019 12:55
-
-
Save dura0ok/f39c5df07125a4f78296b3d26ef067d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'vendor/autoload.php'; | |
use Ratchet\Server\IoServer; | |
use Ratchet\Http\HttpServer; | |
use Ratchet\WebSocket\WsServer; | |
use Ratchet\MessageComponentInterface; | |
use Ratchet\ConnectionInterface; | |
class Chat implements MessageComponentInterface | |
{ | |
protected $clients; | |
public function __construct() | |
{ | |
$this->clients = new \SplObjectStorage; | |
$this->connectedUsers = []; | |
} | |
public function onOpen(ConnectionInterface $conn) | |
{ | |
// Store the new connection to send messages to later | |
$this->clients->attach($conn); | |
$this->connectedUsers [$conn->resourceId] = $conn; | |
$this->connectedIDs[$owner] = $conn->resourceId; // а откуда мы берём owner ? | |
echo "New connection! ({$conn->resourceId})\n"; | |
} | |
public function onMessage(ConnectionInterface $from, $msg) | |
{ | |
$json = (json_decode($msg, true)); | |
$msg = $json['message']; | |
$to = $json['to']; | |
$owner = $json['owner']; | |
$msgData = [ | |
'owner'=> $owner, | |
'message'=> $msg | |
]; | |
$numRecv = count($this->clients) - 1; | |
foreach ($this->clients as $client) { | |
$client->send(json_encode($msgData)); | |
// The sender is not the receiver, send to each client connected | |
//} | |
} | |
} | |
public function onClose(ConnectionInterface $conn) | |
{ | |
// The connection is closed, remove it, as we can no longer send it messages | |
$this->clients->detach($conn); | |
echo "Connection {$conn->resourceId} has disconnected\n"; | |
} | |
public function onError(ConnectionInterface $conn, \Exception $e) | |
{ | |
echo "An error has occurred: {$e->getMessage()}\n"; | |
$conn->close(); | |
} | |
} | |
$server = IoServer::factory(new HttpServer(new WsServer(new Chat())), 8777); | |
$server->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment