PHP Websocket Server that is compatible with socket.io

Overview

PHP SocketIO Server

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']);

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->on(function (\Cydrickn\SocketIO\Socket $socket, callable $next) {
    // ...
    $next();
});

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

$server->on(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->on(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

You might also like...
A multithreaded application server for PHP, written in PHP.

appserver.io, a PHP application server This is the main repository for the appserver.io project. What is appserver.io appserver.io is a multithreaded

Asynchronous server-side framework for network applications implemented in PHP using libevent

phpDaemon https://github.com/kakserpom/phpdaemon Asynchronous framework in PHP. It has a huge number of features. Designed for highload. Each worker i

Framework for building extensible server-side progressive applications for modern PHP.
Framework for building extensible server-side progressive applications for modern PHP.

Chevere 🔔 Subscribe to the newsletter to don't miss any update regarding Chevere. Framework for building extensible server-side progressive applicati

jojo, another http server written in PHP 8.0

جوجو | jojo جوجو، وب‌سروری در ابعاد جوجه برای کارهای کوچک داستان نوشتن جوجو وب‌سروری که تنظیمات مودم TP-link TD-8811 توی اتاقم رو serve میکنه اسمش mic

Socks5 proxy server written in Swoole PHP

php-socks This is a Socks5 proxy server implementation built with PHP & Swoole. To start the proxy server, clone this repo, run composer install to in

💾 High-performance PHP application server, load-balancer and process manager written in Golang. RR2 releases repository.
💾 High-performance PHP application server, load-balancer and process manager written in Golang. RR2 releases repository.

RoadRunner is an open-source (MIT licensed) high-performance PHP application server, load balancer, and process manager. It supports running as a serv

🤯 High-performance PHP application server, load-balancer and process manager written in Golang
🤯 High-performance PHP application server, load-balancer and process manager written in Golang

RoadRunner is an open-source (MIT licensed) high-performance PHP application server, load balancer, and process manager. It supports running as a serv

A pocketmine-mp server that we develop live on Twitch every Saturday from 8pm to 10pm (FR)

Server A pocketmine-mp server that we develop live on Twitch every Saturday from 8pm to 10pm (FR) Contributing Pull requests are welcome. For major ch

Phpactor Language Server

This package provides a platform for building a Language Server according to the Language Server Specification

Releases(v1.6.3)
Owner
Cydrick Nonog
Software Engineer and Gamer
Cydrick Nonog
PHP Web Socket server

Important ⛔️ This project is no longer maintained ⛔️ We urge you to look for a replacement. Description WebSocket Server and Client library for PHP. W

Chris Tanaskoski 346 Nov 8, 2022
A server side alternative implementation of socket.io in PHP based on workerman.

phpsocket.io A server side alternative implementation of socket.io in PHP based on Workerman. Notice Only support socket.io v1.3.0 or greater. This pr

walkor 2.1k Jan 6, 2023
Simple live support server with PHP Swoole Websocket and Telegram API

Telgraf Simple live support server with PHP Swoole Websocket and Telegram API. Usage Server Setup Clone repository with following command. git clone h

Adem Ali Durmuş 6 Dec 30, 2022
Simple WebSocket server implemented in PHP.

Bloatless PHP WebSockets Simple WebSocket server implemented in PHP. Installation Requirements Installation procedure Usage Server Applications Timers

bloatless.org 556 Dec 25, 2022
PHP HI-REL SOCKET TCP/UDP/ICMP/Serial .高可靠性PHP通信&控制框架SOCKET-TCP/UDP/ICMP/硬件Serial-RS232/RS422/RS485 AND MORE!

OHSCE高可靠性的PHP通信框架. Hey!I'm come back! 官方网站:WWW.OHSCE.ORG WWW.OHSCE.COM 最新版本V0.2.0.2 2017-05-10 开发者QQ群:374756165(新2016-09) 捐助: http://www.ohsce.com/ind

null 212 Dec 26, 2022
FreeSWITCH Event Socket Layer library for PHP

FreeSWITCH Event Socket Layer library for PHP Quickstart FreeSWITCH's Event Socket Layer is a TCP control interface enabling the development of comple

rtckit 2 May 10, 2022
FreeSWITCH's Event Socket Layer is a TCP control interface enabling the development of complex dynamic dialplans/workflows

Asynchronous Event Socket Layer library for PHP Quickstart FreeSWITCH's Event Socket Layer is a TCP control interface enabling the development of comp

rtckit 3 Oct 11, 2022
FuelPHP v1.x is a simple, flexible, community driven PHP 5.3+ framework, based on the best ideas of other frameworks, with a fresh start! FuelPHP is fully PHP 7 compatible.

FuelPHP Version: 1.8.2 Website Release Documentation Release API browser Development branch Documentation Development branch API browser Support Forum

Fuel 1.5k Dec 28, 2022
Spiral Framework is a High-Performance PHP/Go Full-Stack framework and group of over sixty PSR-compatible components

Spiral HTTP Application Skeleton Spiral Framework is a High-Performance PHP/Go Full-Stack framework and group of over sixty PSR-compatible components.

Spiral Scout 152 Dec 18, 2022
FrankenPHP is a modern application server for PHP built on top of the Caddy web server

FrankenPHP: Modern App Server for PHP FrankenPHP is a modern application server for PHP built on top of the Caddy web server. FrankenPHP gives superpo

Kévin Dunglas 2.8k Jan 2, 2023