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) { };
websocket.onclose = function(evt) { };
websocket.onmessage = function(evt) { };
websocket.onerror = function(evt) { };
$('#send').click( function(){
websocket.send("This is a testing message");
});
</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?
source
share