0

I am trying to establish a websocket connection with a JavaScript page and php page (LOCALHOST/socket/socket_server2.php).

I start the socket(LOCALHOST/socket/socket_server2.php) and then I open my JavaScript page but the following error is generated:

WebSocket connection to 'ws://localhost/socket/socket_server2.php' failed:

What I am doing wrong?

I am trying this on my local machine with xampp

 <script>
    websocket = new WebSocket('ws://LOCALHOST/socket/socket_server2.php');
   
        websocket.onopen = function(event) { 
            showMessage("<div  >Connection is established!</div>");
            console.log(event)          
        }
        websocket.onmessage = function(event) {
             $("#server").val(event.data);
            //showMessage("<div  >Messaggio dal server:"+event.data+"</div>");
            console.log(event)
             
        };
        
        websocket.onerror = function(event){
            showMessage("<div >Problem due to some Error:"+event+"</div>");
            console.log(event)
        };
        websocket.onclose = function(event){
            showMessage("<div >Connection Closed</div>");
            console.log(event)
            
            // Connection closed.
           // Firstly, check the reason.
            
           if (event.code != 1000) {
              // Error code 1000 means that the connection was closed normally.
              // Try to reconnect.
                
              if (!navigator.onLine) {
                 alert("You are offline. Please connect to the Internet and try again.");
              }
           }
            
            
        }; 
</script>

PHP:

    <?php
    error_reporting(E_ALL);
    /* Allow the script to hang around waiting for connections. */
    set_time_limit(0);
    /* Turn on implicit output flushing so we see what we're getting
     * as it comes in. */
    ob_implicit_flush();
    $port = 8000;
    $address = 'localhost';
    if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
        echo "socket_create() failed: reason1: " . socket_strerror(socket_last_error()) . "\n";
    }
    if (socket_bind($sock, $address,$port) === false) {
        echo "socket_bind() failed: reason2: " . socket_strerror(socket_last_error($sock)) . "\n";
    }
    
    if (socket_listen($sock, 5) === false) {
        echo "socket_listen() failed: reason3: " . socket_strerror(socket_last_error($sock)) . "\n";
    }
    
    socket_set_nonblock($sock); 
    
    do {
        
       
        if (($msgsock = socket_accept($sock)) === false) {
            echo "socket_accept() failed: reason4: " . socket_strerror(socket_last_error($sock)) . "\n";
            break;
        }
     
     
        
        /* Send instructions. */
         
        $msg = "\nWelcome to the PHP Test Server. \n" .
            "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
        socket_write($msgsock, $msg, strlen($msg));
    
       
       
       
        do {
           
          
           
            if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
                echo "socket_read() failed: reason5: " . socket_strerror(socket_last_error($msgsock)) . "\n";
                break 2;
            }
    
            if (!$buf = trim($buf)) {
                continue;
            }
            if ($buf == 'quit') {
                break;
            }
            if ($buf == 'shutdown') {
                socket_close($msgsock);
                break 2;
            }
            $talkback = "PHP: You said '$buf'.\n";
            socket_write($msgsock, $talkback, strlen($talkback));
            echo "$buf\n";
    
             
    
        } while (true);
        socket_close($msgsock);
    } while (true);
    
    socket_close($sock);
    
    
    
     
    ?>   
ADyson
  • 57,178
  • 14
  • 51
  • 63
Daniele
  • 1
  • 1
  • Your PHP appears to create a basic TCP socket, not a websocket. They are not the same thing. [This](https://www.google.com/search?q=php+websocket+server) might help you. – ADyson May 13 '21 at 14:25
  • So this 2 pieces of code can not work together? – Daniele May 14 '21 at 06:59
  • That's correct, yes. You need to use (or implement) some PHP code which runs a WebSocket server, not a plain TCP server. See https://stackoverflow.com/questions/28480575/whats-the-difference-between-websocket-and-plain-socket-communication for more information about the differences between websockets and TCP sockets. – ADyson May 14 '21 at 08:03
  • I just tried to use the code from this guy https://medium.com/@cn007b/super-simple-php-websocket-example-ea2cd5893575 and it works. Probably the code I posted above has some error inside and prevent the connection. Anyway thank you I will read the link you provided. – Daniele May 14 '21 at 09:51
  • `Probably the code I posted above has some error`....no. The problem with the code above is that it doesn't create a websocket. I already explained this. It's not an error, it's just that it does a different task. – ADyson May 14 '21 at 09:54

0 Answers0