Home > database >  Is there any alternate way of web sockets in javascript client side from instead of php
Is there any alternate way of web sockets in javascript client side from instead of php

Time:11-02

Is there any alternate way of web sockets in javascript client side from instead of php.

I am using PHP to communicate but i am want same thing using javascript on client side. Here is my PHP

<?php

    $socket = socket_create(AF_INET, SOCK_STREAM, 0);

    $message = 'hello';
    
    if (!$socket)
    {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);

        print_r("Couldn't create socket: [$errorcode] $errormsg \n");
        die();
    }

    //Connect socket to remote server
    if (!socket_connect($socket,'10.201.1.114', '4000'))
    {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);

        print_r("Could not connect: [$errorcode] $errormsg \n");
        die();
    }

    if (!socket_send($socket, $message, strlen($message), 0))
    {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);

        echo "Could not send data: [$errorcode] $errormsg \n";
        die();
    }

    //echo "Reading response:\n\n";
    $res = '';
    while ($response = socket_read($socket, 4096))
    {
        $res .= $response;
    }

    socket_close($socket);

CodePudding user response:

Agreed, let's not lie to each other, PHP is not the best for websockets for the time being.

Some alternatives I like are :

  • nodejs : basically javascript server side, great ws support.
  • python : with async support you get ws made easy.

These may help :

https://github.com/websockets/ws

https://websockets.readthedocs.io/en/stable/

https://sanicframework.org/en/guide/advanced/websockets.html

Then, if you really want your server made with PHP, you can always just build the websockets server with python or node.js and use messaging tools (like RabbitMQ, REDIS, ...) to relay messages to PHP asynchronously.

CodePudding user response:

One potential solution is to use the WebSocket API. I will provide an example of what that sort of implementation would look like; this will be closer to boilerplate code than a fully functioning example.

function testing() {
  const msg = "some message";
  const socket = new WebSocket("ws://someaddress:port");

  // the socket errored...
  socket.onerror = (event) => {
     console.log("Socket errored: ", event.data);
  };

  // the socket opens...
  socket.onopen = (event) => {
    console.log("Socket opened: ", event.data);

    // since the socket is open, we can send messages now
    socket.send(msg);
  };

  // the socket gets a message
  socket.onmessage = (event) => {
    console.log("Socket messaged: ", event.data);
  };

  // the socket closes...
  socket.onclose = (event) => {
    console.log("Socket closed: ", event.data);
  };
}

testing();
  • Related