Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 30, 2023 02:39 am

Start Using HTML5 WebSockets Today With a PHP Server


One of the exciting new features of HTML5 is WebSockets, which let us talk to the server without using AJAX requests. In this tutorial, we'll review the process of running a WebSocket server in PHP, and then building a client to send and receive messages to it over the WebSocket protocol.


If you want to learn how to use WebSockets with a Node server, check out our companion post.



What are WebSockets?





A WebSocket is a persistent bi-directional communication channel between a client (e.g. a browser) and a back-end service. In contrast with HTTP request/response connections, WebSockets can transport any number of protocols and provide server-to-client message delivery without polling.





What Do WebSockets Replace?


WebSockets are designed to address the limitations of traditional HTTP-based communication. Before the introduction of WebSockets, HTTP requests and responses were stateless, meaning that each request/response pair was independent of previous and subsequent requests/responses. Due to that, it was really difficult to implement real-time communication, where the server needs to push data to the client as soon as it becomes available.


WebSockets also provide advantages over older technologies such as AJAX long polling and server-sent events (SSE). Websockets can replace long-polling easily. This is an interesting concept; the client sends a request to the server–now, rather than the server responding with data it may not have, it essentially keeps the connection open until the fresh, up-to-date data is ready to be sent. The client next receives this, and sends another request. This has its benefits: decreased latency being one of them, as a connection which has already been opened does not require a new connection to be established. However, long-polling isn't really a piece of fancy technology: it's also possible for a request to time-out, and thus a new connection will be needed anyway.


Many AJAX applications make use of the above–this often leads to poor resource utilization.


Wouldn't it be great if the server could wake up one and send data to clients who are willing to listen without some sort of pre-established connection? Welcome to the world of push technology!


Overall, WebSockets is a more efficient and effective solution for real-time communication, and they have become really popular for building real-time web applications.


Install the Ratchet WebSockets Library


Ratchet is a PHP library which enables building real-time, bi-directional, and event-driven applications with WebSockets. Today, we'll use this library to implement the WebSockets server.


To install the Ratchet WebSockets library, you need to use Composer, which is a dependency manager for PHP. Following are the steps to install Ratchet using Composer. I assume that Composer is already installed on your system.


With that in place, you can use the following Composer command to install the Ratchet library.





1
$composer require cboden/ratchet

Upon successful installation, it should create the following composer.json file.























1
{
2
    "require": {
3
        "cboden/ratchet": "^0.4.4"
4
    }
5
}

So, we've installed the Ratchet WebSockets library successfully.


Create the WebSockets Server


In this section, we'll see how to create the WebSockets server in PHP.


Create the server.php file with the following contents.











































































































































































































1
<?php
2
use Ratchet\MessageComponentInterface;
3
use Ratchet\ConnectionInterface;
4
use Ratchet\Server\IoServer;
5
use Ratchet\Http\HttpServer;
6
use Ratchet\WebSocket\WsServer;
7

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

10
class WebSocketsServer implements MessageComponentInterface {
11
    protected $clients;
12

13
    public function __construct() {
14
        $this->clients = new \SplObjectStorage;
15
    }
16

17
    public function onOpen(ConnectionInterface $conn) {
18
        $this->clients->attach($conn);
19
        echo "New connection! ({$conn->resourceId})\n";
20
    }
21

22
    public function onMessage(ConnectionInterface $from, $msg) {
23
        foreach ($this->clients as $client) {
24
            if ($from !== $client) {
25
                $client->send($msg);
26
            }
27
        }
28
    }
29

30
    public function onClose(ConnectionInterface $conn) {
31
        $this->clients->detach($conn);
32
        echo "Connection {$conn->resourceId} has disconnected\n";
33
    }
34

35
    public function onError(ConnectionInterface $conn, \Exception $e) {
36
        echo "An error has occurred: {$e->getMessage()}\n";
37
        $conn->close();
38
    }
39
}
40

41
$server = IoServer::factory(
42
    new HttpServer(
43
        new WsServer(
44
            new WebSocketsServer()
45
        )
46
    ),
47
    8089
48
);
49

50
$server->run();

First of all, we've defined  a WebSocketsServer class, which implements the MessageComponentInterface interface, which provides the necessary callback functions for handling WebSocket events like connections, messages, and disconnections.


Our code then creates a new IoServer instance, which is the main entry point for running a WebSocket server. Finally, it starts the server by calling the run() method of the $server object.


WebSockets Events


WebsSockets is an event-driven protocol. Let's quickly go through an each event defined in the WebSocketsServer class.




  • onOpen(ConnectionInterface $conn): triggered when a new client connects to the WebSocket server. The $conn parameter holds the connection object of the new client. In this method, we've added connections to the $clients storage object.


  • onMessage(ConnectionInterface $from, $msg): one of the most important events. It's triggered when any client sends a message from the client side to the WebSocket server. The $from parameter holds the connection object of the client who sent the message, and $msg is the message content. Also, we loop through all the clients in the $clients storage object and send the message to all clients except the sender client.




  • onClose(ConnectionInterface $conn): triggered when any client disconnects from the WebSocket server. The $conn parameter holds the connection object of the client. In this method, we've removed the connection from the $clients storage object.




  • onError(ConnectionInterface $conn, \Exception $e): triggered when an error occurs on the WebSocket server. The $conn parameter holds the connection object of the client where the error was occurred, and $e is the error object.




Starting the Server


To start the WebSockets server, go ahead and run the following command on command line.





1
$php server.php

Now, our web server is running successfully on port 8089. You can confirm this by running the following command in another tab and it should provide the output as shown in the following snippet.



















1
$telnet localhost 8089
2
Trying 127.0.0.1...
3
Connected to localhost.
4
Escape character is '^]'.

Implement the WebSockets Client


In this section, we'll build an HTML page which connects to the WebSockets server using JavaScript.


Create the client.php file with the following contents.



































































































































































































































































































































































1
<!DOCTYPE html>
2
<html>
3
<head>
4
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
5
<title>WebSockets Client</title>
6
</head>
7
<body>
8
    <div id="wrapper">
9
        <div id="container">
10
            <h1>WebSockets Client</h1>
11
            <div id="chatLog">
12
            </div><!-- #chatLog -->
13
            <p id="examples">e.g. try 'hi', 'name', 'age', 'today'</p>
14
            <input id="text" type="text" />
15
            <button id="disconnect">Disconnect</button>
16
        </div><!-- #container -->
17
    </div>
18

19
    <script>
20
    $(document).ready(function() {
21
      if (!("WebSocket" in window)) {
22
          $('#chatLog, input, button, #examples').fadeOut("fast");
23
          $('<p>Oh no, you need a browser that supports WebSockets. How about <a href="https://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');
24
      } else {
25
          //The user has WebSockets

26
          connect();
27
          function connect(){
28
              var socket;
29
              var host = "ws://localhost:8089";
30
              try{
31
                  var socket = new WebSocket(host);
32
                  message('<p class="event">Socket Status: '+socket.readyState);
33

34
                  socket.onopen = function(){
35
                      message('<p class="event">Socket Status: '+socket.readyState+' (open)');
36
                  }
37

38
                  socket.onmessage = function(msg){
39
                  message('<p class="message">Received: '+msg.data);
40
                  }
41

42
                  socket.onclose = function(){
43
                  message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
44
                  }
45
              } catch(exception){
46
                 message('<p>Error'+exception);
47
              }
48

49
              function send(){
50
                  var text = $('#text').val();
51

52
                  if(text==""){
53
                      message('<p class="warning">Please enter a message');
54
                      return ;
55
                  }
56

57
                  try{
58
                      socket.send(text);
59
                      message('<p class="event">Sent: '+text)
60
                  } catch(exception){
61
                     message('<p class="warning">');
62
                  }
63

64
                  $('#text').val("");
65
              }
66

67
              function message(msg){
68
                $('#chatLog').append(msg+'</p>');
69
              }
70

71
              $('#text').keypress(function(event) {
72
                  if (event.keyCode == '13') {
73
                    send();
74
                  }
75
              });
76

77
              $('#disconnect').click(function(){
78
                 socket.close();
79
              });
80
          }//End connect

81
      }//End else

82
    });
83

84
    </script>
85
</body>
86
</html>
87

88


Let's understand how the above code works.


Firstly, there's the HTML structure of the client-side WebSocket user interface.


After that, there's the JavaScript code which creates the WebSocket connection and implements WebSockets events. When the document is loaded, it checks if the browser supports WebSockets. If it doesn't, a message is displayed to the user to suggest switching to a browser that supports WebSockets, such as Google Chrome.


If the browser supports WebSockets, the connect() function is called, which creates a WebSocket object and connects it to the server running on ws://localhost:8089. The connect() function also defines event listeners for the WebSocket object.


Let's quickly see the event listeners that we've defined for the WebSocket object.




  • onopen: called when the connection is created. It sends a message to the chat area to indicate that the connection is open.


  • onmessage: called when a message is received from the server. It appends the received message to the chat area.


  • onclose: called when the connection is closed. It sends a message to the chat area to indicate that the connection is closed.


Apart from that, we've also built a few helper functions.


The send() function is called when a user enters a message and hits the enter button. It sends the message to the server using the WebSocket object and appends the sent message to the chat area. The message() function is called to append messages to the chat area. Finally, the Disconnect button calls the close() function of the WebSocket object to close the connection.


How to Test the App


As we discussed earlier, go ahead and run the following command on the command prompt to start the WebSockets server.





1
$php server.php

Next, open the http://localhost/client.php in a few different tabs. When the page loads, a WebSocket connection will be opened. So for example, if you've opened this URL in three different tabs, there will be three WebSocket client connections.


Now when you enter the message and press enter in one tab, the same message will be broadcast to other tabs as well by the WebSockets server.


You can click on the Disconnect button to close the WebSocket connection.


So that's how you can use WebSockets in PHP with the help of the Ratchet library.



Original Link: https://code.tutsplus.com/tutorials/start-using-html5-websockets-today--net-13270

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code