Search code examples
phpsocketswebsocketbroadcastphpwebsocket

Websockets : Send message from php server to clients


I'm trying to send messages from my file index.php (server) to clients connected using websockets.

My javascript file to create the client connection :

var websocket_server = new WebSocket("ws://localhost:4950/");
websocket_server.onopen = function(e) {
  console.log("connected");
}
websocket_server.onmessage = function(e)
{
  console.log('message received from server');
}

index.php:

$msg = "Message from server";

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR,1) or die("prbl options\n");
socket_connect($sock, '127.0.0.1', 4950) or die("could not connect\n");
socket_write($sock, $msg, strlen($msg));

The client connect to the websocket is successful, but when I run the PHP file, I get nothing (no error and no message in the console).

In other words, javascript doesn't consider my socket_write as a message :/

Any ideas? :)


Solution

  • I have found a solution thanks to @ADyson ;) I'm using SSE server sent events now and it works !But I'd like to know if my code is 'proper' or if there is a more 'adequate' way.

    I'm using session superglobals to pass server informations changes to another file which is constantly reading it as event-stream (that's the way SSE works).

    index.php :

          <!DOCTYPE html>
          <html lang="en" dir="ltr">
            <head>
              <meta charset="utf-8">
              <script type="text/javascript" src="jquery.js">
              </script>
              <script type="text/javascript" src="stream.js">
              </script>
            </head>
            <body>
          <a>Receive message</a>
            </body>
          </html>
    

    stream.js (listening to the server) :

    var serv = new EventSource("server.php");
    
      serv.onmessage = function(e) {
          var jdata = JSON.parse(e.data);
          console.log(jdata.message);
      };
    
      serv.onopen = function(e) {
            console.log('Connection opened');
      }
    
      $(document).ready(function(){
        $('a').click(function(){
          receive_msg();
        });
      });
    
      function receive_msg(){
        $.ajax({
         type: "POST",
         url: 'controller.php',
         data: {action: 'send'}
       });
      }
    

    controller.php :

        <?php
    session_start();
    if (isset($_POST['action'])) {
      $_SESSION['server']="you have received a message";
    }
    

    server.php :

        <?php
    session_start();
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    
    
    if (isset($_SESSION['server'])) {
      $data = array(
          'message'=> $_SESSION['server']
      );
      $data = json_encode($data);
      echo "data: {$data}\n\n";
      unset($_SESSION['server']);
    }
    

    The way it works :

    Clients connect to the server.php and read the file constantly. When the server wants to send a message to clients, it creates a session variable. Server.php reads the variable and pass it to my js file. Then the variable is destroyed so we pass the message only once.