One way (server2client) simple WebSocket PHP library
composer require gevman/s2c-websocket
$host
- server ip or domain$port
- port for server socket$path
- default path for socket connection$identityParam
- parameter to resolve identity$ssl
- if true will be used wss
protocol, otherwise ws
protocol$AllIdentities
- List of all identities along with params$identity
- Array of identity params of connected user$identity
- Array of identity params of disconnected user$identities
- List of identities which will receive message$message
- message content$host
- Exception object of errorvar webSocket = new WebSocket('ws://example.com:8080/socket/test/id/1/username/test/some-param/some-value');
require __DIR__.'/vendor/autoload.php';
$listener = new \Gevman\PhpSocket\Listener('example.com', 8080, '/socket/test', 'id', false);
$listener->events->onError(function(Exception $e) {
printf('error: %s in %s at line %s', $e->getMessage(), $e->getFile(), $e->getLine());
});
$listener->events->onClientConnect(function($identity) {
printf("Client connected: %s\n\n", $identity['id']);
});
$listener->events->onClientDisconnect(function($identity) {
printf("Client disconnected: %s\n\n", $identity['id']);
});
$listener->events->onMessage(function($identities, $message) {
printf("new message: %s to %s\n\n", $message, implode(',', array_column($identities, 'id')));
});
$listener->events->onUpdate(function($AllIdentities) {
file_put_contents('online-users.txt', array_column($AllIdentities, 'id'));
});
$listener->listen();
$host
- server ip or domain$port
- port of server socket$message
- Message to send$to
- Identity or list identities to be notified, if empty will be notified all identitiesrequire __DIR__.'/vendor/autoload.php';
$notifier = new \Gevman\PhpSocket\Notifier('example.com', 8080);
$notifier->notify(['something' => 'happened', 'new' => 'message'], 1);
var webSocket = new WebSocket('ws://example.com:8080/socket/test/id/1/username/test/some-param/some-value');
webSocket.onmessage(function (message) {
var data = JSON.parse(message.data);
console.log(data.something);
console.log(data.new);
});
For https sites You need use wss
connection, For this You need pass true
for last parameter of Listener constructor and use Apache ProxyPass in Your apache config
ProxyPass /wss ws://example.com:8080
Comments