Reputation: 233
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();
});
Upvotes: 1
Views: 735
Reputation: 1691
I haven't working with socket.io
in php, however I came across this library https://github.com/walkor/phpsocket.io that allows you to implement socket.io
in php. Following the "Simple chat" example should show you how you can set up the server-side code. What you have in your api file doesn't open a server-side connection, rather returns a website that emits data from the client side. Because you don't have a server handling socket connections, it is unable to transmit the data to other sockets. After configuring your server-side socket handler, when the API call is made and the code in your API file is called, the client will receive a webpage with the information you have outputted. In the received data, you are connecting to a socket and emitting data. That data will then be received by the server in the code you implemented following the example I linked, then emit the data to the connections you had set.
Alternatively, rather than making an API call in the first place, why don't you just emit a message instead? This will save you a network call (the API call is unnecessary if all it is doing is triggering the socket) and should make your application faster. It's hard to give exact implementation details without seeing how the API is being called in the first place.
Upvotes: 1