PHP thread not working with HTML5 socket?

It seems that most examples of HTML5 web sockets on the Internet with PHP use a socket plugin. Can I use stream_socket_serverHTML5 with a web socket?

If so, I am trying to create a simple socket server + client with a PHP function stream_socket_server. Here is the code:

PHP Socket Server:

<?php   
$server = stream_socket_server("tcp://localhost:8080", $errno, $errorMessage);

if ($server === false) {
    throw new UnexpectedValueException("Could not bind to socket: $errorMessage");
}

for (;;) {
    $client = stream_socket_accept($server);

    if ($client) {
        echo 'Connection accepted from '.stream_socket_get_name($client, false) . "\n";
        stream_copy_to_stream($client, $client);
    }
}

Web Socket HTML5 Client.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Client Testing</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
    <button id="send">Testing button</button>
    <script>
        websocket = new WebSocket("ws://localhost:8080");
        websocket.onopen = function(evt) { /* do stuff */ }; //on open event
        websocket.onclose = function(evt) { /* do stuff */ }; //on close event
        websocket.onmessage = function(evt) { /* do stuff */ }; //on message event
        websocket.onerror = function(evt) { /* do stuff */ }; //on error event
        $('#send').click( function(){
            websocket.send("This is a testing message"); //send method
        });
        //websocket.close(); //close method
    </script>
</body>
</html>

And this is the return when I connect:

WebSocket connection to 'ws://localhost:8080/' failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE

What did I miss? How to return a valid HTTP response?

+4
source share
1 answer

The shared socket opens at OSI level 4. You open a UNIX socket, TCP socket, UDP socket.

OSI, , ICMP IP, " ".

Websocket - - OSI 7. Websocket ( TCP-) .

. Websocket .

:

+1

Source: https://habr.com/ru/post/1675026/


All Articles