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);
?>