If a wrapper is a the piece of code that can transmit data using a specific protocol, for example WebSocket, a component is the code that will do some work using the received data. For example when the WebSocket wrapper receive a message it will forward it to a component. The component may then decide to forward this data to another client for example. This will be a perfectly valid case for a WebSocket based chat in fact. In order to illustrate how components work, we will build another chat, but this time we will use WebSockets.
Please note that support for components is something that you need to build into your wrappers. You can use the built-in wrappers as examples.
Your WebSocket based component classes will all be inheriting from the abstract WebSocketComponent class. Please go get familiar with it before you continue.
Components must be placed in the app/ directory under a subdirectory of their wrapper. For example WebSocket based components go into app/WebSocket/. The name of our component will be WebChat, so we should put our code inside the file app/WebSocket/WebChat.php.
Ok, now that we have the component file in the correct place, lets see what it would look like. This component will register the webchat protocol in the server, so only WebSocket clients requesting this protocol will be connected to this component.
class WebChat extends WebSocketComponent {
public static $PROTOCOL = "webchat";
private $clients = array();
public function onConnect($con) {
$this->clients[$con->id] = $con;
}
public function onDisconnect($con) {
unset($this->clients[$con->id]);
}
public function onMessage($con, $data, $dataType = 'text') {
foreach ($this->clients as $client) {
if ($client->id != $con->id) {
$client->send($data, ($dataType == 'binary' ? true : false));
}
}
}
}
Suppose that we want to start our server at port 8080 and we want to enable the WebChat component for the host localhost we would have the following config:
$server_config = array(
8080 => array(
'WebSocket' => array(
'hosts' => array(
'localhost' => array('WebChat'),
)
),
'ssl' => array(
'cert_file' => '',
'privkey_file' => '',
'passphrase' => ''
)
)
);
Run the server.php file in a terminal like so php server.php. Run this JavaScript snippet in a browser. It will create 2 WebSocket connections to our server and each of them will send a message. Connection 0 should receive the message from Connection 1 and log it to the console.
for (var x = 0; x < 2; x++) {
(function(x) {
let sock = new WebSocket("ws://127.0.0.1:8080/", "webchat");
sock.onopen = function(e) {
sock.send("Hello from connection " + x);
}
sock.onmessage = function(e) {
console.log("Connection " + x + " received data: " + e.data);
}
sock.onclose = function() {
console.log("Connection closed");
}
})(x);
}
That's it. If you have any questions feel free to open an issue in GitHub.