-
Open the file Applications/Chat/Events.php. Confirm the existing method list and the imports at the top (lines 13–17):
use GatewayWorker\Lib\Gateway;
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
Verify these are present before adding any handler.
-
Add a msg* handler method inside the Events class. Use this exact skeleton:
public static function msgMyType($client_id, $message_data)
{
if ($_SESSION['login'] == true) {
if (!isset($message_data['field'])) {
throw new \Exception("\$message_data['field'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}");
}
Gateway::sendToCurrentClient(json_encode(['type' => 'my_type_response', 'content' => $result]));
return;
}
return;
}
The method name maps directly to type in the client JSON: type: 'my_type' → msgMyType.
-
Choose the correct send method:
| Scenario | Method |
|---|
| Reply to the sender only | Gateway::sendToCurrentClient(json_encode($msg)) |
Reply to a known $client_id | Gateway::sendToClient($client_id, json_encode($msg)) |
| Send to all sessions of a UID | Gateway::sendToUid($uid, json_encode($msg)) |
Broadcast to a group (e.g. 'admins', 'hosts', 'room_1') | Gateway::sendToGroup($group_id, json_encode($msg)) |
-
Read session data using the superglobal $_SESSION (automatically populated by GatewayWorker). Write back with Gateway::setSession($client_id, $_SESSION). Only call setSession during login/auth flows:
$_SESSION['uid'] = $uid;
$_SESSION['login'] = true;
$_SESSION['ima'] = 'admin';
Gateway::setSession($client_id, $_SESSION);
Gateway::bindUid($client_id, $uid);
Gateway::joinGroup($client_id, 'admins');
-
Check UID online before sending (for host-targeted commands):
if (Gateway::isUidOnline($uid)) {
Gateway::sendToUid($uid, json_encode($json));
}
-
Close a client (with optional final payload):
Gateway::closeClient($client_id);
Gateway::closeClient($client_id, json_encode('ok'));
-
Log debug output with Worker::safeEcho (not echo/print):
Worker::safeEcho("[{$client_id}] description {$_SERVER['REMOTE_ADDR']}\n");
-
Run the style fixer and verify no errors before considering the change done:
php vendor/bin/php-cs-fixer fix --dry-run
php vendor/bin/php-cs-fixer fix
php start.php restart