Skip to content

Instantly share code, notes, and snippets.

@Alanaktion
Created October 13, 2017 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alanaktion/421949cc44407a71e0fe1f703156e7a1 to your computer and use it in GitHub Desktop.
Save Alanaktion/421949cc44407a71e0fe1f703156e7a1 to your computer and use it in GitHub Desktop.
Minimal chat server on F3 WS
<?php
require_once 'vendor/autoload.php';
$ws = new \CLI\WS('localhost:8033');
$nicks = [];
// Handle agent connections
$ws->on('connect', function($agent) {
echo sprintf("Client %s connected\n", $agent->id());
print_r($agent->headers());
});
// Handle agent disconnections
$ws->on('disconnect', function($agent) use ($ws, &$nicks) {
$m = json_encode([
"type" => "part",
"clientId" => $agent->id(),
"nick" => @$nicks[$agent->id()]
]);
foreach ($ws->agents() as $client) {
$client->send(\CLI\WS::Text, $m);
}
echo sprintf("Client %s disconnected\n", $agent->id());
});
// Handle receiving data
$ws->on('receive', function($agent, $op, $data) use ($ws, &$nicks) {
$obj = json_decode($data);
switch($obj->type) {
case 'message':
$nick = @$nicks[$agent->id()] ?: $agent->id();
echo sprintf('Client %s [%s]: %s' . "\n", $agent->id(),
$nick, $obj->message);
$m = json_encode([
"type" => "message",
"clientId" => $agent->id(),
"nick" => $nick,
"message" => $obj->message,
]);
break;
case 'nick':
$oldnick = @$nicks[$agent->id()];
echo sprintf('Client %s [%s] set nick to: %s' . "\n",
$agent->id(), $oldnick, $obj->nick);
$nicks[$agent->id()] = $obj->nick;
if($oldnick !== null) {
$m = json_encode([
"type" => "nick",
"clientId" => $agent->id(),
"nick" => $obj->nick,
"oldnick" => $oldnick,
]);
} else {
$m = json_encode([
"type" => "join",
"clientId" => $agent->id(),
"nick" => $obj->nick,
]);
}
break;
}
// Send message, if any
if(isset($m)) {
foreach ($ws->agents() as $client) {
$client->send(\CLI\WS::Text, $m);
}
}
});
$ws->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment