Search code examples
javascriptphpcodeigniterwebsocketratchet

Ratchet Websocket pass a userID


I'm wondering if I could pass an ID on this script

<script>
    var conn = new WebSocket('ws://localhost:8081/');
  conn.onopen = function(e) {
      console.log("Connection established!");
  };

  conn.onmessage = function(e) {
      console.log(e.data);
  };
</script>

and send a userid when creating the variable as such

var conn = new WebSocket('ws://localhost:8081/', <?= $userid ?>);

Is it possible? if it is, how do you use the data on the server side? is it onOpen or is it somewhere else?

I'm totally new to Ratchet and websockets in general, but I'm trying to use ratchet on my Codeigniter4 project, thanks


Solution

  • Try using websocket send() function.

    So It would go somethign like this:

    <script>
        var conn = new WebSocket('ws://localhost:8081/');
      conn.onopen = function(e) {
          console.log("Connection established!");
      };
    
      conn.onmessage = function(e) {
          console.log(e.data);
      };
    
      // send user id to the server
      conn.send(<?= $userid ?>);
    </script>