Basic WebSocket Client Example
A simple PHP WebSocket client that connects to the chat server.
Client Code
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Sockeon\Sockeon\Connection\Client;
// Create client
$client = new Client('localhost', 8080);
// Set up event handlers
$client->on('welcome', function($data) {
echo "Welcome: {$data['message']}\n";
echo "Your client ID: {$data['clientId']}\n";
});
$client->on('chat.message', function($data) {
echo "[{$data['from']}]: {$data['message']}\n";
});
$client->on('user.connected', function($data) {
echo "{$data['message']}\n";
});
$client->on('user.disconnected', function($data) {
echo "{$data['message']}\n";
});
$client->on('user.typing', function($data) {
if ($data['typing']) {
echo "User {$data['clientId']} is typing...\n";
}
});
$client->on('error', function($data) {
echo "Error: {$data['message']}\n";
});
// Connect to server
try {
$client->connect();
echo "Connected to WebSocket server\n";
// Send a message
$client->emit('chat.message', [
'message' => 'Hello from PHP client!'
]);
// Keep connection alive and listen for messages
$client->run();
} catch (Exception $e) {
echo "Failed to connect: " . $e->getMessage() . "\n";
}
How to Run
- Make sure the WebSocket server is running first
- Save the code as
client.php
- Run the client:
php client.php
Features
- Event Handling: Listens for various server events
- Message Sending: Sends chat messages to the server
- Connection Management: Handles connection and disconnection
- Error Handling: Catches and displays connection errors
Server Events Handled
welcome
- Welcome message from serverchat.message
- Chat messages from other usersuser.connected
- When a new user joinsuser.disconnected
- When a user leavesuser.typing
- Typing indicatorserror
- Error messages from server
Usage
The client will:
- Connect to the WebSocket server
- Send an initial "Hello" message
- Listen for incoming messages
- Display all chat activity in the console