I am working on codeigniter rest api,and at the sametime i need to push some count message via socket, so i have written js code using echo (to run js code in php we need echo), but socket code is not working, i.e at receiver side I am not getting any message.
socket code in rest api file:
if ($this->db->insert('users', $new_arr)) {
echo '<script src="' . base_url("node_modules/socket.io/node_modules/socket.io-client/socket.io.js") . '"></script>';
echo " var socket = io.connect( 'http://'+window.location.hostname+':3000' )";// open connection at sender
echo 'socket.emit("new_count_message", { // emit message
new_count_message: 145
})';
$response = array('status' => true, 'message' => 'data dded successfully', 'response' => array());
} else {
$response = array('status' => true, 'message' => 'Failed to add data!');
}
$this->response($response);
At rceiver:
var socket = io.connect( 'http://'+window.location.hostname+':3000' );// connection open at receiver
socket.on( 'new_count_message', function( data ) {
alert(data.new_count_message);
$( "#new_count_message" ).html( data.new_count_message );
$('#notif_audio')[0].play();
});
httpserverunder "Minimal working example". Basically, the connection needs to be open as long as the server is running, and is separate from the webpage generated and returned from your API. Your rest api file is "emitting" to nothing, as it isn't connected to any active socket.io.connect()method inside of there is looking to connect to an open socket, not open one. If you're opening it somewhere else, please include that code as well, or correct me if I'm missing something.websockets, however anytime I've usedsocket.io(in node), I have always emitted a message from a client to a server, and then the server would emit the message to the appropriate clients. I'm not aware of any way to emit from one client directly to another without a server, which is what your code seems to be doing. Your API file doesn't seem to be serving as the server socket connection, it's just returningHTMLso that the client can connect to asocket, but that opensocketisn't in this code. Try github.com/walkor/phpsocket.io?