Parece que la mayoría de los ejemplos de socket web HTML5 en línea con PHP están usando el complemento de socket. ¿Es posible usar stream_socket_server con socket web HTML5?
En caso afirmativo, estoy tratando de construir un servidor de socket simple + cliente con la función PHP stream_socket_server . Aquí está el código:
Servidor de socket PHP:
<?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); } }Cliente de socket web HTML5.
<!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>Y este es el retorno cuando me estoy conectando:
WebSocket connection to 'ws://localhost:8080/' failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE¿Qué me he perdido? ¿Cómo devuelvo una respuesta HTTP válida?
Recibe este error ERR_INVALID_HTTP_RESPONSE porque no envía la respuesta apropiada a través de su socket.
Una respuesta del servidor al cliente se ve así:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chatEntonces necesitas escribir eso en el socket:
socket_write($accept, $httpResponse); También necesita implementar el sondeo a través socket_select() , actualmente su programa no puede manejar más de una sola conexión.
Además, no olvide usar socket_close() cuando haya terminado.
Respuesta antigua
Se abre un socket genérico en la capa 4 de OSI. Se abre un socket UNIX, un socket TCP, un socket UDP.
También es posible abrir sockets en capas inferiores de OSI, como ICMP o incluso IP, que generalmente se denominan "zócalos sin procesar".
Un Websocket es un protocolo de capa de aplicación: capa 7 de OSI. Un Websocket utiliza un socket genérico (conexión TCP dúplex simple) para enviar y recibir sus datos.
No puede conectar uno con el otro sin una implementación adicional. Un Websocket se basa en un socket normal.
Ver: