How can I integrate node.js and socket IO in code igniter.
<script>
// create a new websocket
var socket = io.connect('http://localhost:8000');
// on message received we print all the data inside the #container div
socket.on('notification', function (data) {
var usersList = "<dl>";
$.each(data.users,function(index,user){
usersList += "<dt>" + user.user_name + "</dt>\n" +
"<dd>" + user.user_description + "\n" +
"<figure> <img class='img-polaroid' width='50px' src='" + user.user_img + "' /></figure>"
"</dd>";
});
usersList += "</dl>";
$('#container').html(usersList);
$('time').html('Last Update:' + data.time);
});
</script>
As mentioned in this SO question here. My view file with codeigniter is in localhost/myproject
but nodejs listen to port using localhost:8000
. So how can I connect socket IO
. Like
var socket = io.connect('http://localhost:8000');
//here I need to make socket IO listen to localhost/myproject instead of localhost:8000 .
How is this possible?
I think you're misunderstanding how the socket.io works. You would never listen to your CI view. You would always be sending messages to (and receiving messages from) the NodeJS server on port 8000. Codeigniter's views are simply static, and there is no reason to "listen" to it since it will only load once.
The key point from that answer you referenced:
users will use codeigniter URL and when open the page, i have this script on my CI view page that connects to my Nodejs app
Therefore, you load your browser with the CI view, then listen for events from the NodeJS server through the JavaScript in your CI view.
You can then also push events to the NodeJS server from the JavaScript in your CI view.
Use Dnode, it is an asynchronous RPC system for node.js that makes it talk to php (and vice versa) directly (php side you can call on your codeigniter controller)
I wrote a linkedin post recently about this
https://www.linkedin.com/pulse/make-php-nodejs-talk-each-other-serdar-senay
In the tutorial written for dnode by its founder there's some stale code, so use the code sample in my linkedin post, also dumped below (with better formatting than linkedin):
require ('vendor/autoload.php');
$loop = new React\EventLoop\StreamSelectLoop();
// Connect to DNode server running in port 7070 and call argument with Zing 33
$dnode = new DNode\DNode ($loop);
$dnode-> connect (7070, function ($remote, $connection) {
// Remote is A That Provides Proxy object Methods us all from the Server
$remote-> zing(33, function ($n) Use ($connection) {
echo "n = {$n}\n";
// Once We Have the Result We Can close the connection
$connection->end();
});
});
$loop-> Run();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With