定制 cydrickn/socketio 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

cydrickn/socketio

Composer 安装命令:

composer require cydrickn/socketio

包简介

PHP Websocket Server that is compatible with socket.io

README 文档

README

PHP Websocket Server that is compatible with socket.io

So far the function use in this package is almost same with the naming in socket.io

Installation

composer require cydrickn/socketio

Then in your main php code add

require __DIR__ . '/../vendor/autoload.php';

Usage

Initializing your server

To initialize

$server = new \Cydrickn\SocketIO\Server([
    'host' => '0.0.0.0',
    'port' => 8000,
    'mode' => SWOOLE_PROCESS,
    'settings' => [
        \Swoole\Constant::OPTION_WORKER_NUM => swoole_cpu_num() * 2,
        \Swoole\Constant::OPTION_ENABLE_STATIC_HANDLER => true,
    ]
]);

$server->on('Started', function (\Cydrickn\SocketIO\Server $server) {
    echo 'Websocket is now listening in ' . $server->getHost() . ':' . $server->getPort() . PHP_EOL;
});

$server->on('connection', function (\Cydrickn\SocketIO\Socket $socket) {
    // ...
});

$server->start();

Server Options

Key Details Default
host The host of the server 127.0.0.1
port The port of the server 8000
mode The mode for server 2 / SWOOLE_PROCESS
sock_type The socket type for server 1 / SWOOLE_SOCK_TCP
settings The setting is base on swoole configuration [] / Empty Array

Server Instance

This is the server \Cydrickn\SocketIO\Server, it also inherited all methods of \Cydrickn\SocketIO\Socket

Events

Basic Emit

To emit, just need to call the \Cydrickn\SocketIO\Socket::emit

$server->on('connection', function (\Cydrickn\SocketIO\Socket $socket) {
    $socket->emit('hello', 'world');
});

You can also pass as many as you want for the parameters

$socket->emit('hello', 'world', 1, 2, 3, 'more');

There is no need to run json_encode on objects/arrays as it will be done for you.

// BAD
$socket->emit('hi', json_encode(['name' => 'Juan']));

// GOOD
$socket->emit('hi', ['name' => 'Juan']);

Broadcasting

Broadcast is like just the simple emit, but it will send to all connected client except the current client

$socket->broadcast()->emit('hi', ['name' => 'Juan']);

Sending to all clients

The toAll will emit a message to all connected clients including the current client

$socket->toAll()->emit('hi', ['name' => 'Juan']);

Acknowledgements

Same with the socket io for nodejs, you just need to add a callable as the last argument in the emit

Server

$socket->emit('hi', function () {
    //...
});

Client

socket.on('hi', (callback) => {
    callback('hello');
});

With Timeout

Assign a timeout to each emit:

// timeout for 5 seconds
$socket->timeout(5000)->emit('hi', function (bool $err) {
    if ($err) {
        // the other side did not acknowledge the event in the given delay
    }
});

Add callback default arguments value for timeout

// timeout for 5 seconds
$socket->timeout(5000, 'Juan')->emit('hi', function (bool $err, string $name) {
    var_dump($name); // if the other side did not acknowledge the event the $name will be 'Juan'
    if ($err) {
        // the other side did not acknowledge the event in the given delay
    }
});

Listening

To listen to any event

$server->on('hello', function (\Cydrickn\SocketIO\Socket $socket, string $world) {
    // ...
});

$server->on('hi', function (\Cydrickn\SocketIO\Socket $socket, array $name) {
    // ...
});

Server Event

This event can't be use for the route Since this event are Swoole Websocket Event All Event with * should not be used

  • Request - When you use it for http
  • *WorkerStart - You must not replace this event since this is the worker start logic for this package
  • *Start - You must not replace this event since this is the start logic for this package
  • *Open - You must not replace this event since this is the connection logic for this package
  • *Message - You must not replace this event since this is the message logic for this package
  • *Close - You must not replace this event since this is the message logic for this package

Rooms

In this package it was already included the rooms

To join to group just call the function join

$socket->join('room1');

To emit a message

$socket->to('room1')->emit('hi', ['name' => 'Juan']);

Emit to multiple room

$socket->to('room1')->to('room2')->emit('hi', ['name' => 'Juan']);

Leaving the room

$socket->leave('room1');

Sending to specific user

In socket.io javascript, the user was automatically created a new room for each client sid.

But currently in this package it will not create a new room for each client.

In this package you just need to specify if its a room or a sid

use Cydrickn\SocketIO\Message\Response;

$socket->on('private message', (\Cydrickn\SocketIO\Socket $socket, $anotherSocketId, $msg) => {
    $socket->($anotherSocketId, Response::TO_TYPE_SID).emit('private message', $socket->sid, $msg);
});

Middleware

You can add an middleware for the server

$server->use(function (\Cydrickn\SocketIO\Socket $socket, callable $next) {
    // ...
    $next();
});

To not continue the connection you just pass \Error in the $next

$server->use(function (\Cydrickn\SocketIO\Socket $socket, callable $next) {
    // ...
    $next(new \Error('Something went wrong'));
});

You can also add middleware for handshake event of Swoole Server. Just passed true to the second argument.

Also in callback it will pass the response for you to modify if you need it

$server->use(function (\Cydrickn\SocketIO\Socket $socket, \Swoole\Http\Response $response, callable $next) {
    // ...
}, true);

If you want to create a middleware as a class we recommend to implement the Cydrickn\SocketIO\Middleware\MiddlewareInterface and if for handshake use Cydrickn\SocketIO\Middleware\HandshakeMiddlewareInterface

Example of middleware that use in handshake is the Cydrickn\SocketIO\Middleware\CookieSessionMiddleware. This middleware will create a session that uses the cookie and if the client did not send the session cookie then it will create a cookie and response it from the handshake.

Session

In this package the there is already session storage that you can use,

  • SessionsTable - Uses the Swoole\Table as the storage
  • SessionsNative - Uses the file storage

Using Swoole, session_start, $_SESSION should not be use since this function are global it stores the data in the process itself.

The session that provided here does not use this predefined session extensions. Currently, the session is define per connection so you can take the session via.

$socket->getSession();

This getSession can return null if you don't have any middleware that creating the session.

To set a session

$session = $server->getSessionStorage()->get('123456'); // This will automatically created once it does not exists
$socket->setSession($session);

You can also customize your session storage, just implement the Cydrickn\SocketIO\Session\SessionStorageInterface

<?php

class CustomeStorage implements SessionStorageInterface {
    // ...
}

After creating your storage

You need to pass this in your server constructor

$server = new \Cydrickn\SocketIO\Server([
    'host' => '0.0.0.0',
    'port' => 8000,
    'mode' => SWOOLE_PROCESS,
    'serve_http' => true,
    'settings' => [
        \Swoole\Constant::OPTION_WORKER_NUM => swoole_cpu_num() * 2,
        \Swoole\Constant::OPTION_ENABLE_STATIC_HANDLER => true,
        \Swoole\Constant::OPTION_DOCUMENT_ROOT => dirname(__DIR__).'/examples'
    ]
], sessionStorage: new CustomeStorage());

Example

TODO

This package was used in

cydrickn/socketio 适用场景与选型建议

cydrickn/socketio 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.29k 次下载、GitHub Stars 达 28, 最近一次更新时间为 2022 年 09 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 cydrickn/socketio 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 cydrickn/socketio 我们能提供哪些服务?
定制开发 / 二次开发

基于 cydrickn/socketio 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2.29k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 28
  • 点击次数: 16
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 28
  • Watchers: 1
  • Forks: 6
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-09-09