Skip to content
This repository has been archived by the owner on Sep 10, 2024. It is now read-only.

7. Websocket

Albert Chen edited this page Oct 21, 2019 · 25 revisions

WebSocket

This is a very important feature of this package. Generally in Laravel when you want to build a WebSocket server, you have to rely on third-party WebSocket server. The most common way is to use Pusher or Socket.io provided by NodeJS and with the combination of Broadcasting. There's no way to build a WebSocket server in Laravel.

Now with Swoole, it is possible and not difficult to integrate with Laravel. Nowadays when we talk about WebSocket, the majority choose Socket.io to be their solution. The good news is this package is compatible with Socket.io protocol (partially). That means in the browser or other clients you can use Socket.io client directly.

These Socket.io features are not implemented:

  • namespace
  • path
  • long polling
  • sid (sid interacts with servers will be ignored)
  • only supports non-binary type data

WebSocket Event Binding

After you run vendor:publish, you can find websocket.php in your routes folder. This is where you can register your WebSocket events. It looks pretty much like how you register an HTTP route in Laravel. You can register events with on function, and it supports callback function or handler path.

<?php

use SwooleTW\Http\Websocket\Facades\Websocket;

/*
|--------------------------------------------------------------------------
| Websocket Routes
|--------------------------------------------------------------------------
|
| Here is where you can register Websocket events for your application.
|
*/

Websocket::on('connect', function ($websocket, $request) {
    // in connect callback, illuminate request will be injected here
    $websocket->emit('message', 'welcome');
});

Websocket::on('disconnect', function ($websocket) {
    // this callback will be triggered when a websocket is disconnected
});

Websocket::on('example', function ($websocket, $data) {
    $websocket->emit('message', $data);
});

Websocket::on('test', 'ExampleController@method');

In callback functions, you can get $websocket and $data as parameters.

Parameter sequence doesn't matter, but parameter names does.

Middleware for onConnect Event Request

connect is a special event which will be triggered after the WebSocket connection is established. You can do some authorization here according to the request. Here you can use middleware for pre-processing the request. The default middleware are set in config/swoole_websocket.php.

'middleware' => [
    SwooleTW\Http\Websocket\Middleware\DecryptCookies::class,
    SwooleTW\Http\Websocket\Middleware\StartSession::class,
    SwooleTW\Http\Websocket\Middleware\Authenticate::class,
],

There are some built-in middleware for fetching auth user with session guard. You can customize your middleware for your authorization.

Middleware will be executed by sequence. Getting a session auth user needs to decrypt cookies first, then start a session, and finally get auth user.

Websocket::on('connect', function ($websocket, $request) {
    $request->user();
    auth()->user();
});

Getting authorized user is as easy as what you usually do in Laravel.

Websocket::on('connect', function ($websocket, $request) {
    //
})->middleware(FooBarMiddleware::class);

You can also append your middleware after the on function.

In onConnect event, you can't make any HTTP response back to the client here. Here's just a callback function after the connection established.

Authenticated User Binding

After getting the authenticated user, you can bind the user to established socket connection. You can choose to emit events to the specific user, and all bound sockets will receive the message.

// bind a user to current socket, user must implement AuthenticatableContract class
Websocket::loginUsing($user);

// bind a user using user id
Websocket::loginUsingId($userId);

// get current auth user id by sender's fd
Websocket::getUserId();

// emit message to specific user
Websocket::toUser($user)->emit('message', 'hi there');

// emit message to multiple users
Websocket::toUser([$userA, $userB])->emit('message', 'hi there');

// emit message to specific user id
Websocket::toUserId($userId)->emit('message', 'hi there');

// emit message to multiple user ids
Websocket::toUserId([$userId1, $userId2])->emit('message', 'hi there');

WebSocket APIs

Function Parameters Description
on string $event, callable $callback Listen to a event name, and bind to handler
broadcast None Set current message to broadcast
to int string array $values Assigned to specific or multiple fds or rooms
loginUsing Authenticatable $user Bind user to current socket
loginUsingId string $uid Bind user id to current socket
logout None Logout by current sender's fd
getUserId None Get current auth user id by sender's socket
toUser Authenticatable $user or array Set multiple recipients' fds by users
toUserId string $userId or array Set multiple recipients' fds by userIds
isUserIdOnline string $userId Check if there's any online sockets with this user id
join string array $rooms Join current sender to one or multiple rooms
leave string array $room Make current sender leave one or multiple rooms
emit string $event, mixed $data Emit an event with data
close None Close current connection
getSender None Get current sender's fd
getIsBroadcast None Get if is broadcast now
getTo None Get assigned fds and rooms
reset boolean $force Reset isBroadcast, to and sender (if force is true)

Usage Examples

The usage of Websocket refers to Socket.io, so they look highly similar and friendly for those developers who have experience in Socket.io.

<?php

use SwooleTW\Http\Websocket\Facades\Websocket;

// sending to sender-client only
Websocket::emit('message', 'this is a test');

// sending to all clients except sender
Websocket::broadcast()->emit('message', 'this is a test');

// sending to all clients in 'game' room except sender
Websocket::broadcast()->to('game')->emit('message', 'nice game');

// sending to all clients in 'game1' and 'game2' rooms except sender
Websocket::broadcast()->to('game1')->to('game2')->emit('message', 'nice game');
Websocket::broadcast()->to(['game1', 'game2'])->emit('message', 'nice game');

// sending to all clients in 'game' including sender client
Websocket::to('game')->emit('message', 'enjoy the game');

// sending to individual socketid 1 (can't be sender)
Websocket::broadcast()->to(1)->emit('message', 'for your eyes only');

// sending to socketid 1 and 2 (can't be sender)
Websocket::broadcast()->to(1)->to(2)->emit('message', 'for your eyes only');
Websocket::broadcast()->to([1, 2])->emit('message', 'for your eyes only');

// join to subscribe the socket to a given channel
Websocket::join('some room');

// leave to unsubscribe the socket to a given channel
Websocket::leave('some room');
<?php

use SwooleTW\Http\Websocket\Facades\Room;

// get all fds in a 'game' room
Room::getClients('game');

// get all rooms of fd 1
Room::getRooms(1);

// add fd 1 to a 'game' room
Room::add(1, 'room');

// add fd 1 to 'game' and 'test' rooms
Room::add(1, ['game', 'test']);

// delete fd 1 from a 'game' room
Room::delete(1, 'room');

// delete fd 1 from 'game' and 'test' rooms
Room::delete(1, ['game', 'test']);

Customization

Default handler uses Socket.io, but you can still use your customized WebSocket protocol.

There are two classes you need to deal with:

  • Websocket Handler: Need to implement HandlerContract
<?php

namespace SwooleTW\Http\Websocket;

use Illuminate\Http\Request;
use Swoole\Websocket\Frame;

interface HandlerContract
{
    /**
     * "onOpen" listener.
     *
     * @param int $fd
     * @param \Illuminate\Http\Request $request
     */
    public function onOpen($fd, Request $request);

    /**
     * "onMessage" listener.
     *  only triggered when event handler not found
     *
     * @param \Swoole\Websocket\Frame $frame
     */
    public function onMessage(Frame $frame);

    /**
     * "onClose" listener.
     *
     * @param int $fd
     * @param int $reactorId
     */
    public function onClose($fd, $reactorId);
}
  • Packet Parser: Need to extend Parser
<?php

namespace SwooleTW\Http\Websocket\Foo;

use Swoole\Websocket\Frame;
use SwooleTW\Http\Websocket\Parser;

class FooParser extends Parser
{
    /**
     * Strategy classes need to implement handle method.
     */
    protected $strategies = [
        // optional
    ];

    /**
     * Encode output message for websocket push.
     *
     * @return mixed
     */
    public function encode($event, $data)
    {
        // your formatting logic
        return $result;
    }

    /**
     * Decode message from websocket client.
     * Define and return payload here.
     *
     * @param \Swoole\Websocket\Frame $frame
     * @return array
     */
    public function decode(Frame $frame)
    {
        // your formatting logic
        return [
            'event' => $yourParsedEventName,
            'data' => $yourParsedData
        ];
    }
}

And configure them with your class path in config/swoole_websocket.php

'handler' => SwooleTW\Http\Websocket\SocketIO\WebsocketHandler::class,
'parser' => SwooleTW\Http\Websocket\SocketIO\SocketIOParser::class,

← Commands | Facades →