CODE | DEMO*
UPDATE: This is the third of a three part series on CodeIgniter, Redis, and Socket.IO integration. Please be sure to read the other posts as well.
Part 1: A Sample CodeIgniter Application with Login And Session
Part 2: Use Redis instead of MySQL for CodeIgniter Session Data
Part 3: You are here.
Well here it is, folks, the moment I’ve been waiting for :) Real-time updates that actually work! Socket.IO has been integrated to work its magic alongside CodeIgniter. Now when a user is logged in, updates will tumble in like an avalanche with absolutely no refreshes or any user intervention at all! To catch up on what this is all about, be sure to check out A Sample CodeIgniter Application with Login And Session and Use Redis instead of MySQL for CodeIgniter Session Data before reading this.
Take a look at the video above to see the live updates in action. There are three different browser windows open (Chrome, Firefox, and IE9), each logged in with a different user. The top left browser is the Admin, which will get updated when any user posts a message. The Admin is also a member of team one, so when the admin posts a message, members of team one (bottom left) will see it. The browser on the right is team two, so she will not see anyone else’s posts, but the Admin will see what she posts.
* The demo may or may not be working depending on the state of my VPS. Most of my sample projects so far have been hosted on my shared hosting account, but due to the Redis and Node requirement I had to deploy this project to a VPS that I normally use for development and testing. If I am doing some development or testing, then Apache or Node or Redis might not be working properly – hence the video. Your best option really, is to download the code and try it yourself!
The Socket.IO library makes it painfully easy to work with NodeJS (aka, Node). Prior to this project I knew almost nothing about Node other than what had read in a few short books. I still don’t know much about Node, but I know that I like it and will continue to keep investigating it for future projects. One thing in particular that I think pretty cool in this project, is that all of the Node specific functionality (the real-time message updates) runs mostly parallel to the PHP application. So if Node decides to blow up, the application will still work, only without live updates.
Anyway, enough jibber jabber. Here’s the rundown on the changes to the application, and the highlights of the Socket.IO and Node code. Again, this is not meant to be a tutorial, but rather a show and tell and perhaps a nice piece of code for others to experiment with. Use at your own risk.
Installing Socket.IO
First things first: Install Socket.IO. I already had Node and NPM installed, but I needed a spot to create the node ‘server’ within my project. I created a folder in the project root called ‘nodejs’. Through the wonders of Node Package Management (NPM), I installed the socket.io package, as well as the node_redis package. This was done by simply navigating to the nodejs folder and running:
npm install redis
Yeah, that’s it. NPM will create a folder called ‘node_modules’ and download all the dependencies necessary to run the packages. After that I created the cisockServer.js file, and I was off to the races.
To get things working right away, I added code similar to the following, just to get things rolling. The first line instantiates Socket.IO and gets a Node server up and running on port 8080. An event handler is created for the ‘connection’ event, which fires whenever a Socket.IO client connects to the server. When this happens, Socket.IO will emit an event with an identifier of ‘startup’ and attach an object with a message. If the client is listening for the ‘startup’ event, it will receive the message.
io.sockets.on('connection', function (socket) {
// Let everyone know it's working
socket.emit('startup', { message: 'I Am Working!!' });
});
To actually get the Node server fired up, it’s as easy as node --debug cisocketServer.js
to get it going. I added the –debug option because I was using node-inspector for debugging and tracing. There is also an interesting project called Forever available from NodeJitsu that manages one or more Node processes. I use it on my VPS. It’s nice.
The Socket.IO Client
A server is all fine-and-dandy, but it won’t do much good without clients. I created a new javascript file in my CodeIgniter assets folder called ‘socket.js’ to hold all of my Socket.IO related client code. I wrapped most of the code in the MY_Socket namespace so it is more easily accessed by the javascript in main.js. The minimum amount of code needed to work with the server code above is what follows. It simply creates a socket connection, then listens for the ‘startup’ event from the socket connection. When the ‘startup’ event occurs, the attached message will be displayed on the console.
window.MY_Socket = {
// Instantiate the Socket.IO client and connect to the server
socket : io.connect('http://localhost:8080'),
// Set up the initial event handlers for the Socket.IO client
bindEvents : function() {
this.socket.on('startup',MY_Socket.startupMessage);
},
// This just indicates that a Socket.IO connection has begun.
startupMessage : function(data) {
console.log(data.message);
}
} // end window.MY_Socket
// Start it up!
MY_Socket.bindEvents();
});
To get this working, all that is needed are a couple more lines in header.php:
<script src="<?php echo base_url();?>/assets/js/socket.js"></script>
Now upon visiting the login screen (or any screen, really), the words, “I am working!” will appear in the console.
Joining A Room
Socket.IO has a concept called rooms, which is a nice way to segment broadcasted messages from a server so only a subset of users receive the message. In this application, users will join a room based on their team numbers. Team 1 will join room 1, and so on. The exception here are admins. Admin users can be on a team, but will receive messages from all users regardless of their team. To handle this, I created another room called ‘admin’.
The room joining process starts when a user is logged in. I added a bit of jQuery code to check the current page for team badges, and if any are found, run the joinRoom function. Another way to do this would be to just put a call to MY_Socket.joinRoom() at the top of /application/views/main.php so it runs whenever the main view is loaded.
...
if($('.userTeamBadge').children().length > 0){
MY_Socket.joinRoom();
}
}
So the joinRoom function does some interesting things. First it grabs the cookie named, “ci_session” and reads the value. This value is the session ID set by CodeIgniter. This ID will be used to look up some of the other session information stored in Redis by the application’s MY_Session class. When the session ID is obtained, a ‘joinRoom’ event is emitted with the ID attached. If no session ID is found, then nothing happens. The code below is part of the client code in the socket.js file.
// get the CodeIgniter sessionID from the cookie
var sessionId = readCookie('ci_session');
if(sessionId) {
// Send the sessionID to the Node server in an effort to join a 'room'
MY_Socket.socket.emit('joinRoom',sessionId);
} else {
// If no sessionID exists, don't try to join a room.
console.log('No session id found. Broadcast disabled.');
//forward to logout url?
}
}
Socket.IO will be listening for the ‘joinRoom’ event on the server. When it hears the event, it will grab the session ID, use it to construct a string that matches the corresponding session key in the Redis database, and get the data associated with that key. The results returned from Redis will contain the rest of the user’s session information, including teamId and isAdmin (indicating if the user is or is not an admin). The result is parsed into a JSON, and the teamId and isAdmin values are used to join the appropriate ‘rooms’.
For any of this to work, a Redis client must be set up to execute Redis commands. The following code is in cisockServer.js.
var io = require('socket.io').listen(8080);
// Let Node know that you want to use Redis
var redis = require('redis');
// Listen for the client connection event
io.sockets.on('connection', function (socket) {
// Instantiate a Redis client that can issue Redis commands.
var rClient = redis.createClient();
// Handle a request to join a room from the client
// sessionId should match the Session ID assigned by CodeIgniter
socket.on('joinRoom', function(sessionId){
var parsedRes, team, isAdmin;
// Use the redis client to get all session data for the user
rClient.get('sessions:'+sessionId, function(err,res){
console.log(res);
parsedRes = JSON.parse(res);
team = parsedRes.teamId;
isAdmin = parsedRes.isAdmin;
// Join a room that matches the user's teamId
console.log('Joining room ' + team.toString());
socket.join(team.toString());
// Join the 'admin' room if user is an admin
if (isAdmin) {
console.log('Joining room for Admins');
socket.join('admin');
}
});
});
});
Excellent.
Send and Receive Messages
When a user posts a new message, the data is sent to the web server using jQuery’s Ajax function. This happens in the App.postMessage function in the main.js file. If the post is successful, a callback function – App.successfulPost – is executed. In order for the post to be successful, it needs to be processed by the CodeIgniter controller method responsible for saving posts to the database. This method – main.post_message – had to be refactored so that it would not only save the message, but also respond to jQuery’s ajax request with the message wrapped up in the HTML template so it can be sent out to other users.
The HTML template responsible for rendering each individual message was separated out into its own view and saved as /application/views/single_posts.php. It was basically just cut and pasted from the main view.
<div class="otherAvatar">
<img src="../../assets/img/avatars/<?php echo $avatar ?>.png"
alt=""
data-title="<span class='badge badge-info'><?php echo $teamId ?></span> <?php echo $firstName ?> <?php echo $lastName ?>"
data-content="<?php echo $tagline ?>">
</div>
<div class="otherPostInfo">
<div class="otherPostBody"><p><?php echo $body ?></p></div>
<hr/>
<div class="otherPostDate"><p class="pull-right"><?php echo $createdDate ?></p></div>
</div>
</div>
In order to populate that template, CodeIgniter’s Loader.view method was used with the third parameter set to ‘true’ so it will return data instead of immediately rendering the view in the browser. The view is then loaded into the response data as a string, along with the user’s teamId value, and the HTML string that will be prepended to the user’s own message list. The following code is from /application/controller/main.php (the Main controller).
... save message to db code ...
if ( isset($saved) && $saved ) {
// Gather up data to fill the message template
$post_data = array();
$post_data = $this->user_m->fill_session_data($post_data);
$post_data['body'] = $saved['body'];
$post_data['createdDate'] = $saved['createdDate'];
// Create a message html partial from the 'single_post' template and $post_data
$broadcastMessage = $this->load->view('single_post',$post_data,true);
// Create an html snipped for the user's message table.
$myMessage = "<tr><td>". $saved['body'] ."</td><td>". $saved['createdDate'] ."</td></tr>";
// Create some data to return to the client.
$output = array('myMessage'=>$myMessage,
'broadcastMessage'=>$broadcastMessage,
'team'=>$post_data['teamId']);
// Encode the data into JSON
$this->output->set_content_type('application/json');
$output = json_encode($output);
// Send the data back to the client
$this->output->set_output($output);
}
}
The response object is sent back to the jQuery callback function, and it begins the process of broadcasting the message out to all the appropriate users. This really only takes one extra line of code in App.successfulPost.
...
// Send socket.io notification
MY_Socket.sendNewPost( result.broadcastMessage, result.team );
}
All this does is send two pieces of information to the MY_Socket.sendNewPost function. The MY_Socket.sendNewPost function will simply take the message and teamId value and send it to the Node server by emitting a Socket.IO event.
MY_Socket.socket.emit('newPost',msg,team);
}
When the ‘newPost’ event is handled on the server, it will relay the message to the appropriate team room, and also to the ‘admin’ room.
console.log('Broadcasting a post to team: ' + team.toString());
// Broadcast the message to the sender's team
var broadcastData = {message: post, team: team};
socket.broadcast.to(team.toString()).emit('broadcastNewPost',broadcastData);
// Broadcast the message to all admins
broadcastData.team = 'admin';
socket.broadcast.to('admin').emit('broadcastNewPost',broadcastData);
});
The ‘broadcastNewPost’ event is emitted twice, and will therefore be handled twice by the client. This is not normally a problem, unless there is an admin with the same teamId as the sender. Then the admin will receive the message twice, and duplicate messages will be displayed on the screen. To correct this, a little logic prevents the message from being displayed twice. The message attached to the ‘broadcastData’ object is forwarded to the App.showBroadcastedMessage function.
updateMessages : function(data) {
// Because the message is broadcasted twice (once for the team, again for the admins)
// we need to make sure it is only displayed once if the Admin is also on the same
// team as the sender.
if( ( !userIsAnAdmin() && data.team != 'admin') ||
( userIsAnAdmin() && data.team === 'admin') ){
// Send the html partial with the new message over to the jQuery function that will display it.
App.showBroadcastedMessage(data.message);
}
}
When the App.showBroadcastedMessage function receives the message, it appends it to the top of the list of messages from other users using simple jQuery.
$(messageData).hide().prependTo(App.$otherMessages).slideDown('slow');
//App.$otherMessages.prepend(messageData);
App.setElements();
App.setupComponents();
}
Whew. That’s it! The journey is complete.
April 15, 2013 at 12:33 pm
Eric,
This is really neat and actually something I was thinking about, over the weekend, after starting a new project. Although I did not know how to go about implementing it, I knew that something like Node would work great!! I cannot wait to really dig into this(there’s a lot here to digest). Like you, I have played with Node and have a real interest in working with it more. This looks like as good as any place to start.
Thanks for sharing this and the hard work that went into it!
April 15, 2013 at 6:21 pm
Hey Phillip, thanks! Glad you enjoyed it. I agree, it probably is a lot to digest, but I tried to leave many helpful comments in the code and highlight the most important bits in the blog articles. Let me know if you have any questions.
April 21, 2013 at 8:06 am
Hi Eric, thanks for this, i’ve been looking for an example of node.js /codeignighter/ socket.io for weeks and found your example, thanks again. I am trying to run your example but i have come across an error i can’t resolve. I get the following fatal error in MY_Session.php on $this->redis = new Redis();
Fatal error: Class ‘Redis’ not found in C:\Users\sure\wamp\www\ci_sock-master\part_three\application\libraries\MY_Session.php on line 34
it can create an instance of Redis but i am not sure what i need to do so it finds Redis();
has anyone come across this, thanks again.
April 21, 2013 at 10:03 am
Hey Jack, glad you found some interest in this! Did you get phpredis installed? phpredis is the PHP extension that contains the Redis class that is instantiated in My_Session.php. If you don’t have phpredis installed yet, take a look at step 2 of this article: Use Redis instead of MySQL for CodeIgniter Session Data. The code is available here: https://github.com/nicolasff/phpredis
April 22, 2013 at 3:08 pm
Hi Eric,
I was looking for that kind of stuff since a month and this is a really great tutorial, now I have to do it on my way.
One question : Can we do it without PHP redis ? Redis is installed but this is not the same about phpextension ( A lot of compiler error in my output). Can we do it with an other way ?
Thanks you so much for this share, it is really helpful for me. Great work !
Simon
April 22, 2013 at 3:45 pm
Hi Eric thanks for your response, i knew i wasn’t doing something right, “if only I had paid more attention…” i’m on windows so will try building phpredis on Windows, thanks again.
April 22, 2013 at 8:58 pm
@Simon, you don’t need to use Redis. I used it because it is a fast and easy way to share information between PHP and Node. You can use mySQL instead of Redis and use the default Session class from CodeIgniter. You will need to install a mySQL package for Node in order to read the session information from the database.
Another thing to look into is elephant.io. It is a PHP client for Socket.IO. That would also allow you to share information between Node and your PHP application. I’ve never used it, but it looks like it can be useful.
May 10, 2013 at 11:29 am
Hi Eric This is super cool!, thanks for sharing your app will be very helpfull for the world!
May 18, 2013 at 10:21 am
Eric,
Excuse me sir, where is sendNewPost come from?
When i change sendNewPost to sendNewPost1 , the console in firebug show me “TypeError: MY_Socket.sendNewPost1 is not a function”
thanks
May 21, 2013 at 9:40 am
You provide your example to download?
May 21, 2013 at 7:51 pm
@Flavio the code can be downloaded at https://github.com/ericterpstra/ci_sock/part_three
@Heren, MY_Socket.sendNewPost() is called at the end of the successfulPost callback function in assets/js/main.js (line 198)
The successfulPost function is called when a message is successfully sent to the server via jQuery’s ajax function (see main.js line 108)
May 24, 2013 at 10:08 am
Hi Eric, that’s awesome !! Thanks
I can run part one perfectly , but got some error on part three when loading the login page
(Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
Line Number: 346)
Please advice
May 24, 2013 at 1:31 pm
https://github.com/ericterpstra/ci_sock/part_three Page 404
May 24, 2013 at 10:57 pm
Sorry, just go here: https://github.com/ericterpstra/ci_sock/ and take a look at part_three
May 24, 2013 at 10:59 pm
Did you follow the steps to install Redis in part 2? Also, check the settings in /application/config/database.php and make sure it is correct for your system.
June 10, 2013 at 6:48 am
Hi Eric,
I really thanks a lot for the post and your perfect example. This is what I need, but i faced with one problem.
My problem is, redis and redisphp. I have Xampp on my PC and I don’t have any idea how to install it. I saw some examples and adivce, but I don’t know if I did it good.
My error now show like this:
Fatal error: Class ‘Redis’ not found in C:\xampp\htdocs\ci_sock\part_three\application\libraries\MY_Session.php on line 33
I suppose that I don’t install correctly the redis and redisphp in my XAMPP. Do you have any advice?
Thanks a lot
June 10, 2013 at 11:22 am
@Mani Please read “Part 2: Use Redis instead of MySQL for CodeIgniter Session Data” for instructions on installing the Redis class for PHP. The instructions are different depending on your operating system (Windows, Linux or OSX).
https://ericterpstra.com/2013/03/use-redis-instead-of-mysql-for-codeigniter-session-data/
Also, here are detailed instructions for building phpredis on Windows:
https://github.com/nicolasff/phpredis/issues/213#issuecomment-11361242
June 10, 2013 at 12:55 pm
Eric,
Thanks for response.
I read the 3 tutorials in details, but in the Part 2, I don’t see any instructions on installing the Redis class for PHP for the Windos (XAMPP).
Also I wanna ask, is there any way for building phpredis on windows without visual studio. Can we do maybe with installing something, and edit php.ini, because I don’t have Visual Studio, because in PHP I don’t need it.
Thanks a lot
June 10, 2013 at 5:05 pm
@Mani, unfortunately I do not use Windows for development, so beyond the link I provided, I do not know. Visual Studio Express is free to download from Microsoft. If you really want to install the Redis class, why not try it?
Also, I just found this: https://github.com/nicolasff/phpredis/downloads
It looks like phpredis_5.4_vc9_nts.7z may be the compiled .dll
June 28, 2013 at 12:58 pm
Hi Eric,
I really want to thank you for these tutorials. I can’t install the Redis, but I did with CI Session, and get your application, analyze and implement a lot of your advice on my app.
Your code is very clear and well documented, and it was my pleasure to analyze and learn from it.
You was my first tutorials for node.js and sockets and I want to thank you a lot for that.
Hope that soon I will have pleasure to read more blogs from you.
June 29, 2013 at 9:49 pm
hello eric,
this is nice tutorial, but i had some problem with database connection, when i start the app part three, it display an error like this =>
“Unable to connect to your database server using the provided settings.
Filename: C:\xampp\htdocs\ci_sock\part_three\system\database\DB_driver.php
Line Number: 124”.
my redis is running and i had configure the database.php, please can you give any advice ?
July 1, 2013 at 2:22 pm
@sozhuke Try deleting config/database-local.php if it exists, and double check your config/database.php settings.
July 2, 2013 at 7:50 pm
it work, great, thank you for your help, eric
July 23, 2013 at 8:09 am
HI Eric,
Thanks for your tutorial is perfect, i have one question i follow your post but when y try to use the MY_Session class i have problem with codeigniter and only i can see a error 500, and all aplication no work.
if i change the name in config.php $config[‘subclass_prefix’] by other prefix (ej GT_) the aplication work again, but i don”t use the extended session class. if i put again in config file the prefix MY_ the application no work no open any link. I search for this problem but i can’t found a solution, can you helpme?
Thanks
July 24, 2013 at 11:19 pm
hi Eric,
Your online demo seems not working, I couldn’t log in, then I try download the source and run in my server its also not working, at the end, a could log in by disable My_session.php, but it’s mean code not working as its should be.
Please help me, why the custom session library not working,, ty..
July 25, 2013 at 9:12 am
Hi Eric,
My problem wass i have to disable SELinux in centos and work, i follow this guide http://wiki.centos.org/HowTos/SELinux#head-ad837f60830442ae77a81aedd10c20305a811388
and this http://stackoverflow.com/questions/8765848/troubleshooting-permission-denied-when-attempting-to-connect-to-redis-from-php
and your application work!! thank for this, is perfect and i will use in my apps!!
Thanks ! :)
August 24, 2013 at 9:04 am
Hi Eric,
How are you?
I check the Demo now, and it is not working real time now. I don’t know why? Before it works good.
I have the same problem like you now?
I upload online my real time status update (based on your example). I install node and socket. I use 8080 port online, but it didn’t work, and I dont know why. In your example is happen the same.
Which port I need to use to work at all users when whey login.
Can you check your example aganin, and tell me which port need to use, and what need to do to work online.
ON MY LOCALHOST it works perfect! It based on your example, I just adapt on my way and it works very nice. Online NOT!
August 24, 2013 at 9:23 am
Hi Mani, the node process was stopped on my server because I’ve been doing some work on there. Sorry. I have restarted it and it works for me now.
I use port 80 for Apache on my server, and 8080 for the Socket.IO connection. You need to make sure that port 8080 is open on your server. Also, make sure you change the URL in /assets/js/socket.js on line 5 to match your server name.
August 24, 2013 at 10:53 am
Thanks a lot for fast reply. You really help me a lot to understand node and sockets.
When I upload, I change the socket.js like this:
// Instantiate the Socket.IO client and connect to the server
socket : io.connect(‘http://server_ip:8080’), // server_ip is my Server IP
Did I do it correct?
So, I need to make sure that the port is open. Can I open it for all users that open that page? Or I need to open for specific IP’s?
Thanks a lot again
August 24, 2013 at 12:29 pm
Mani, you changed the code correctly, although you might want to try the domain name instead of the IP instead.
The port needs to be open to whomever is going to access the page, because the browser will connect to it.
August 26, 2013 at 3:46 pm
Eric,
I fix my problem. Thanks a lot for everything. You help me a lot, and also reply fast and complete answers.
Thanks a lot again!
September 19, 2013 at 2:21 am
Love it !! can’t wait to implement this on my project ,,
June 9, 2014 at 1:17 am
Hi Eric.. is that can work if i not using redis and just using ci session?
July 16, 2014 at 9:37 am
Hi, Great tutorial and exactly what I needed. I got the demo to run in a vhost and it was working great, with all 3 demo users each in a different browser (chrome, firefox and safari) and all was rocking out.
So I moved the code into my development codeigniter instance and ported it all into my tree and fired it up again. All of it works, except Im having to reload pages to see the updates. Redis tests ok with my CI install, node is running the socket server app, the node modules are installed, everything works like it should and looks right in the network console for the posts and all that, but no real time, only updates for each users message lists from other users on page refreshes. What have I done wrong?
Also – Im going to try and make this thing multiplex capable next, so that a user can “private message” another user on demand from a user list – using something like their IP or user Id or session id or something as their “team id” to direct messages to the right recipients. Have you done any of that or do you have any suggestions for tackling that functionality with this code base?
thanks
Corky
July 16, 2014 at 10:39 am
Nevermind about the real time not working after porting into my existing codeigniter tree. I fixed it. I use codeigniter bonfire for auth management and my CI cookie is called bf_session instead of ci_session so I had to change that in socket.js on line 58 or so… Whew!
Fixed it!
Now on to user selectable channels (team ids)
September 16, 2014 at 1:29 pm
Hi Eric.
Thanks a lot for your hard work.
Your tut is awesome!
I think my question will be very stupid but I spend 3 days on this tut to test your app.
Your app work but :
– I need to refresh the page to see new posts from a other user (instant update doesn’t work here at home on my VirtualMachine running Debian. IP of the VM : 192.168.0.19)
– I get this error:
(translated from french with google translate)
A multi-origin request (Cross-Origin Request) was blocked: the “Same Origin” policy does not refer to the remote resource on http://192.168.0.19:8080/socket.io/1/?t= 1410890548538. This can be corrected by moving the resource on the same domain oractivant CORS.
here is a part of my socket.js
socket : io.connect(‘http://192.168.0.19:8080’),
here is a part of my config.php
$config[‘redis_host’] = ‘localhost’;
$config[‘redis_port’] = ‘6379’;
Do you think I did something wrong?
I use CI for a while but I’m not really skilled with unix.
So maybe I did something wrong when I tried to setup redis and phpredis.
Could you help one of your fan? :D
September 16, 2014 at 6:03 pm
@lipo
Sounds like you are accessing your site with a URL that is different from your IP address. In your browser, are you using ‘http://localhost’ or ‘http://192.168.0.19’?
Becuase of the Cross Domain Access Poilicies of browsers, you must have the URL of your browser be the same as the resources you are trying to reach. So if you use ‘http://localhost’ in your browser, change io.connect to socket : io.connect(‘http://localhost:8080′)
Read more about Cross domain access here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
September 17, 2014 at 6:35 am
PS:
my VM is running Debian
March 22, 2015 at 12:24 pm
Hi eric, i already try this tutorial on windows environment with xampp, redis, phpredis, socket.io installed with no problem and running very well on my codeigniter configuration, but live update is not running, i got an error like this on my chrome console “GET http://localhost:80/socket.io/1/?t=1427044614910 404 (Not Found)”, i already change the port with available port that open on my computer, and get that an error result again.
can you give me advice to solve the problem, thanks
April 1, 2015 at 4:54 am
Hello everyone.
I was very pleased to find this tutorial. It allowed me to build a chat like facebook on my application developed with Codeigniter. The chat is private (multichannel) and is accessible from all pages of the site, so people can communicate in private by using a small window on the bottom. It works very well locally. But I have a problem when I transferred the application on a dedicated server.
Could someone help me please?
I encounter an error of type Cross Origin.
I can not integrate CORS in the code by Eric because the documentation uses Express. https://www.npmjs.com/package/cors
I’m searching for days on forums but I didn’t found any solution.
Can you devote me few minutes of your precious time to help me please.
Here is my server-side code:
'Log level': 1
});
// Let Node Know That you want to use Redis
var repeat = require ('repeat');
var ent = require ('ent');
mysql var = require ('mysql');
var mysqlclient mysql.createConnection = (
{
host: 'localhost'
user: 'xxxx',
password: 'xxxx',
database: 'xxxx'
}
);
// Listen for the customer login event
io.sockets.on ('connection', function (socket) {
// My app instructions on server side
}
Here is my client side code:
window.MY_Socket = {
// Instantiate the Socket.IO Client and connect to the server
socket: io.connect ('http://my-domain-without-www.com:8080')
// My app instructions on client side
}
April 1, 2015 at 7:54 am
Hi everybody,
I solved half the problem by changing the port 8080 to 80 on the client side…
It was under my eyes for days, sorry for the post.
The cross origin error is solved but I’ve a new problem on the server side. If I try to listen on the port 80
'log level':1
});
I get this error:
Error: listen EADDRINUSE
Please tell me if I’m wrong because I’m a noob :)
I think the server use the port 80 to serv the php app.
So when we try to connect this port with socket.io there is a conflict right?
Is there a solution ?
Or is it just not possible to use CI + Socket.io for production environment?
April 1, 2015 at 8:48 am
totof: Yes, it is definitely possible to run CI and Socket.io in production. Port 80 is in use by Apache. I would recommend running your node application on port 8080 (or which ever port you choose), and using Apache’s ‘ProxyPass’ feature to proxy requests from socket.io client to your server through port 80 to port 8080.
I haven’t done this myself in a very long time, so I cannot give you specific instructions, but take a look at these articles on setting up Apache as a reverse proxy for Node:
http://blog.podrezo.com/making-node-js-work-with-apache/
http://thatextramile.be/blog/2012/01/hosting-a-node-js-site-through-apache/
April 1, 2015 at 9:28 am
Hi Eric,
thank you very much for your answer. I think ‘ProxyPass’ could be a good solution. I will work on it and I give you news if I manage to fix it.
Your tuto is great, thank you for sharing :)
PS: you’ve “dead links” on this page : https://ericterpstra.com/2013/04/live-updates-in-codeigniter-with-socket-io-and-redis => need to delete 2013/04
Hope it will be usefull for you.
April 20, 2015 at 2:27 am
hi, your tutorials looks great but when i run your demo… i not feel it is a real-time… each time i have to refresh the page to see the message send by the team 1 on admin and from admin to team 1… your example working but not as real time… i don’t know why…
May 4, 2015 at 2:07 am
Hey,
I have finally installed your code on my server and it is working fine. Can you please tell me how can I keep the socket connection always “on”.
As soon as I logout from my server the code stops working.
Please help.
Thanks
Keshav
May 4, 2015 at 8:58 am
To keep your server running
npm install forever
then start your server.js with the command : forever start server.js
May 4, 2015 at 9:01 am
Hey totof,
Thanks a lot for the reply.
I already figured it out. And Yes, I used “forever” to get it done.
Regards
Keshav
June 23, 2015 at 6:54 am
Hello,
Thanks for the nice n very detailed article.
Really a big thank to you!!!!! Marvelous…!
December 29, 2015 at 10:44 pm
I downloaded your code and tried on my localhost , but whenever i try to run node ciSockServer.js its shows nothing, and when i open it in browser i get Class ‘Redis’ not found.
January 4, 2016 at 8:27 pm
Did you read part 2 and install the Redis Class? Also, this article is very old and the code may no longer work.