gevman / s2c-websocket
单向(服务器到客户端)简单的WebSocket PHP库
1.0.1
2016-12-21 19:24 UTC
Requires
- php: >=5.4
This package is auto-updated.
Last update: 2024-09-21 03:01:59 UTC
README
单向(服务器到客户端)简单的WebSocket PHP库
安装(使用composer)
composer require gevman/s2c-websocket
监听方法
构造函数(string $host, int $port, string $path, string $identityParam, bool $ssl)
创建监听器
$host
- 服务器IP或域名$port
- 服务器套接字端口$path
- 套接字连接的默认路径$identityParam
- 解析身份的参数$ssl
- 如果为true,将使用wss
协议,否则使用ws
协议
void listen()
开始监听
void onUpdate(function(array $AllIdentities) {/* */})
当用户连接或断开连接时触发
$AllIdentities
- 带有参数的所有身份的列表
void onClientConnect(function(array $identity) {/* */})
当用户连接时触发
$identity
- 连接用户身份参数的数组
void onClientDisconnect(function(array $identity) {/* */})
当用户断开连接时触发
$identity
- 断开连接用户身份参数的数组
void onMessage(function(array $identities, string $message) {/* */})
当服务器发送消息时触发
$identities
- 将接收消息的身份列表$message
- 消息内容
void onError(function(Exception $e) {/* */})
错误时触发
$host
- 错误的异常对象
示例
客户端(JavaScript)
var webSocket = new WebSocket('ws://example.com:8080/socket/test/id/1/username/test/some-param/some-value');
服务器端(PHP)
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();
通知方法
构造函数(string $host, int $port)
创建通知器
$host
- 服务器IP或域名$port
- 服务器套接字端口
bool notify(mixed $message, mixed $to)
向服务器发送消息,该消息将被发送到列出的身份
$message
- 要发送的消息$to
- 要通知的身份或身份列表,如果为空,将通知所有身份
示例
服务器端(PHP)
require __DIR__.'/vendor/autoload.php'; $notifier = new \Gevman\PhpSocket\Notifier('example.com', 8080); $notifier->notify(['something' => 'happened', 'new' => 'message'], 1);
客户端(JavaScript)
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); });
对于HTTPS网站,您需要使用wss
连接。为此,您需要将监听器构造函数的最后一个参数传递为true
,并在您的Apache配置中使用Apache ProxyPass。
ProxyPass /wss ws://example.com:8080