Created
August 30, 2013 09:57
-
-
Save J7mbo/6388265 to your computer and use it in GitHub Desktop.
ALMOST awesomeness
This file contains hidden or 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 | |
// EchoEndpoint.php | |
use Aerys\Handlers\Websocket\Message, | |
Aerys\Handlers\Websocket\Endpoint, | |
Aerys\Handlers\Websocket\WebsocketHandler, | |
Alert\Reactor, | |
Amp\JobDispatcher, | |
Amp\CallResult; | |
class EchoEndpoint implements Endpoint { | |
const RECENT_MSG_LIMIT = 10; | |
const RECENT_MSG_PREFIX = '0'; | |
const USER_COUNT_PREFIX = '1'; | |
const USER_ECHO_PREFIX = '2'; | |
private $websocketHandler; | |
private $sockets = []; | |
private $recentMessages = []; | |
private $dispatcher; | |
private $reactor; | |
function __construct(WebsocketHandler $websocketHandler, Reactor $reactor, JobDispatcher $dispatcher) { | |
$this->websocketHandler = $websocketHandler; | |
$this->dispatcher = $dispatcher; | |
$this->reactor = $reactor; | |
$this->dispatcher->connectToJobServer('127.0.0.1:1338'); | |
} | |
function onOpen($socketId) { | |
$this->sockets[$socketId] = $socketId; | |
$this->websocketHandler->sendText($socketId, 'HERRO'); | |
$this->broadcastUserCount(); | |
$this->sendUserRecentMessages($socketId); | |
} | |
private function sendUserRecentMessages($socketId) { | |
$recipient = $socketId; | |
$msg = self::RECENT_MSG_PREFIX . json_encode($this->recentMessages); | |
$this->websocketHandler->sendText($recipient, $msg); | |
} | |
private function broadcastUserCount() { | |
$recipients = array_values($this->sockets); | |
$msg = self::USER_COUNT_PREFIX . count($this->sockets); | |
$this->websocketHandler->sendText($recipients, $msg); | |
} | |
function onMessage($socketId, Message $msg) { | |
$payload = $msg->getPayload(); | |
// Only keep the last N messages in memory | |
if (array_unshift($this->recentMessages, $payload) > self::RECENT_MSG_LIMIT) { | |
array_pop($this->recentMessages); | |
} | |
$recipients = $this->sockets; | |
// Don't send this message to the client that originated it! | |
//unset($recipients[$socketId]); | |
$msg = self::USER_ECHO_PREFIX . $payload; | |
$dispatcher = $this->dispatcher; | |
$dispatcher->call(function(CallResult $result) use($recipients) { | |
var_dump($result->getResult()); // This puts it into Aerys terminal window | |
$this->websocketHandler->sendText($recipients, $result->getResult()); // This doesn't do bollocks | |
}, 'test', 1); | |
} | |
function onClose($socketId, $code, $reason) { | |
unset($this->sockets[$socketId]); | |
$this->broadcastUserCount(); | |
} | |
} | |
// and the test function which is included via --include for amp.php | |
function test() | |
{ | |
sleep(5); | |
return "omg it worked"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment