Introduction

Usage

"Controlling complexity is the essence of computer programming." Brian Kernighan


Overview

Considerations:

  • Messages must be in JSON format.
  • The message must contain the action key corresponding to the action being triggered. e.g. {action: 'broadcast-action'}.
  • If a simple non-JSON string is sent, it will be considered a “ping/pong”, responding with the same message that was sent. This is the “base-action”.

Following we have 4 examples:

  • Case 1: The simple case: messages happen in ping/ping fashion between client and server and won’t broadcast to other clients. (base-action)
  • Case 2: The channel case: messages get broadcasted to all other clients within the same channel. If the client is not connected to a channel, it will be broadcast to everybody not connected to channels.
  • Case 3: The listener case: where clients can filter which messages (by action) they will receive. This is useful when you have custom actions.
  • Case 4: Associate an application user id with a connection (fd). This will keep in memory the information of which user_id (integer) owns which file descriptor (fd – integer).

Case 1: Simple Case

Simple Case

At this example the user will receive back a real-time message from the server after sending a message.

At this library, there is the presumption that the socket message has a JSON format, if not, the ConveyorActionsBaseAction will be the handler and the text will be added as the “data” parameter of that action. That said, the following standard is expected to be followed by the messages in general, so they can match specific Actions. The minimum format is this:

1{
2    "action": "base-action",
3    "data": "here goes other fields necessary for the Actions processing..."
4}

Thats it! Now, to communicate in real-time with this service, on your HTML you can do something like this:

1<div>
2    <div><button onclick="sendMessage(JSON.stringify({
3            'action': 'base-action',
4            'data': 'first',
5        }))">Base Action</button></div>
6    <div><button onclick="sendMessage('second')">Simple Text</button></div>
7    <div id="output"></div>
8</div>
9<script type="text/javascript">
10    var websocket = new WebSocket('ws://127.0.0.1:8080');
11    websocket.onmessage = function (evt) {
12        document.getElementById('output').innerHTML = JSON.parse(evt.data).data;
13    };
14    function sendMessage(message) {
15        websocket.send(message);
16    }
17</script>

Notice that these 2 buttons result in the same action.

This is what it looks like:

Simple Case Example

Case 2: Using Channels

Using Channels

At this case it is possible for clients sharing a channel to communicate to each other by broadcasting messages and data through this channel.

The procedure here requires one extra step during the instantiation: the connection action. The connection action will link in a persistent manner the connection FD to a channel.

Notice that if you use the fanout action, it will broadcast to any other connection outside of channels. It will only broadcast messages to other clients within the same channel if you use the broadcast action.

If you are using any Conveyor client package you won’t need to manually connect to a channel at the right moment by yourself as the client already does that by a configuration parameter. To connect manually, you can send the following message:

1{
2    "action": "channel-connect",
3    "channel": "channel-name"
4}

After connecting to a channel, all messages sent by that client will be within that channel. You can disconnect from a channel by sending this message:

1{
2    "action": "channel-disconnect"
3}

As an example, we have the following HTML example. When connected, the given connection will participate on a given channel:

1<div>
2    <form id="message-form" onsubmit="return sendMessage()">
3        <div>
4            <input id="message-box" autocomplete="off" type="text" placeholder="The message goes here..."/>
5        </div>
6        <input type="submit" value="Submit"/>
7    </form>
8
9    <div>
10        <ul id="output"></ul>
11    </div>
12</div>
13<script type="text/javascript">
14    var channel = 'actionschannel';
15    var websocket = new WebSocket('ws://127.0.0.1:8080');
16    websocket.onopen = function(e) {
17        // connect to a channel
18        websocket.send(JSON.stringify({
19            'action': 'channel-connect',
20            'channel': channel,
21        }));
22    };
23    websocket.onmessage = function (evt) {
24        document.getElementById('output').innerHTML = evt.data;
25    };
26    function sendMessage() {
27        websocket.send(JSON.stringify({
28            'action': 'broadcast-action',
29            'data': document.getElementById('message-box').value,
30        }));
31        return false;
32    }
33</script>

That’s all, with this, you would have the following:

Using Channels Example

Case 3: Associate User With Connection

This functionality is for applications that need to have associations between connections (fd) and users. This is useful when you need to execute actions that need to know the user and decide upon that. One good example is a server that serves at the same time multiple users, but won’t answer users the same way depending on the procedure executed. That way, you can have actions that will process some data and broadcast to connections only what each connection needs to receive for that procedure.

For this functionality, you only need one extra action to be dispatched:

1{
2    "action": "assoc-user-to-fd-action",
3    "userId": 1,
4}

This code will associate the user “1” with the current connection.

Advice: It is recommended to use some token or secret to identify them before the WebSocket server accepts the association. To see a good example, you can check it here: Authorization.

Case 4: Use Middlewares

The usage of middleware might help to secure your WebSocket server, making sure specific validations and conditions are met in order to proceed. At Socket Conveyor, middlewares are attached to actions at the socket router’s instance. The way to do that is as follows:

1<?php
2
3use Conveyor\Conveyor;
4use OpenSwoole\WebSocket\Frame;
5use OpenSwoole\WebSocket\Server;
6
7$websocket = new Server('0.0.0.0', 8080);
8
9$websocket->on('message', function (Server $server, Frame $frame) use ($persistenceService) {
10    Conveyor::init()
11        ->server($server)
12        ->fd($frame->fd)
13        ->addMiddlewareToAction('broadcast-action', function ($payload) {
14            echo "Received broadcast: " . $payload['data'];
15            return $payload;
16        )
17        ->closeConnections()
18        ->run($frame->data);
19});
20
21$websocket->start();

This is a simple example of implementing your OpenSwoole server with Conveyor with a custom middleware that echoes incoming messages.

The Payload is an array with 2 keys:

  • data: The actual message coming in.
  • user: The user id if that was associated.

Case 5: Fanout Action

This is a global broadcast that goes outside the borders of the channels.

Important: when a client is listening to actions other than the one you send, that client won’t receive it. It happens because listeners are “filters”.

1<div>
2    <div><button onclick="sendMessage('Hello')">Say Hello</button></div>
3    <div id="output"></div>
4</div>
5<script type="text/javascript">
6    var websocket = new WebSocket('ws://127.0.0.1:8080');
7    websocket.onmessage = function (evt) {
8        document.getElementById('output').innerHTML = JSON.parse(evt.data).data;
9    };
10    function sendMessage(message) {
11        websocket.send(JSON.stringify({
12            'action': 'fanout-action',
13            'data': message
14        }));
15    }
16</script>

Messages sent with this example will be broadcasted to any client regardless of channels.

Previous
Installation