I have one PHP server that is listening to "messages" from some remote PHP clients. Once a message is received by the server, The server is supposed to update a GUI using javascript web sockets on localhost. The PHP server is receiving messages correctly. The problem is when the server attempts to send the message to the Javascript client, I keep getting the error "Firefox can’t establish a connection to the server at ws://127.0.0.1:6002/." and error code 1006.
PHP Server code.
// socket used between PHP clients and PHP server
$srv_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($srv_socket, SOL_SOCKET, SO_REUSEADDR, TRUE);
socket_bind($srv_socket, "10.10.10.2", 6001);
socket_listen($srv_socket);
// socket used between PHP server and Web GUI (javascript)
$gui_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($gui_socket, SOL_SOCKET, SO_REUSEADDR, TRUE);
socket_bind($gui_socket, "127.0.0.1", 6002);
socket_listen($gui_socket);
while (TRUE) {
// get message from PHP client
$client_socket = socket_accept($srv_socket);
$message = socket_read($client_socket, 250);
socket_close($client_socket);
if ($message != NULL) {
echo "Message Received: " . $message . ".";
// send message to GUI
$gui_client_socket = socket_accept($gui_socket);
socket_write($gui_client_socket, $message, strlen($message));
echo "Message Sent to GUI.";
}
}
Javascript Client code.
$(document).ready(function(){
var socket = new WebSocket("ws://127.0.0.1:6002/");
socket.onopen = function(ev) {
alert('socket connection opened properly');
};
socket.onmessage = function(ev) {
var message = ev.data;
alert("message arrived!");
};
socket.onerror = function(error){
alert("Error: " + error.message);
};
socket.onclose = function(ev){
alert("Connection closed: " + ev.code);
};
});
The output from the PHP server is Message Received: {"msg":"Hello World!"}. Message Sent to GUI.
The output from Javascript is two alerts: 1st alert: "Error: undefined" 2nd alert: "Connection closed: 1006"
Please NOTE I am running Debian, and I have flushed my iptables with iptables -F
and then added two rules for ports 6001 and 6002.
iptables -A INPUT -p tcp -m tcp --dport 6001 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 6002 -j ACCEPT
IMPORTANT
I am running the PHP server from terminal and not from Apache. example: php -q /var/www/html/php_server.php
, while the Javascript client is attempting to open a websocket on ws://localhost:6002/
Am I missing something? Am doing doing something wrong? Ultimately, I need that javascript client to receive the message from the PHP server. Any help will be highly appreciated, thank you.