Socket.IO:Real time notification using socket.IO in codeigniter

real-time-notification-using-socket.io-in-codeigniter

In this post i would like to show how we can implement a real time notification system using socket.io in codeigniter application. Socket.io is a powerful javascript library which enable real time notification, instant messaging and all other real time events.

What is  socket.IO?

Socket.io is a javascript library which enable realtime notification, instant messaging,online gaming and all other real time events.It works on every platform browser or device.

Installation of Socket.IO in Codeigniter:

To get started with socket.io we need to have node installed.To install socket.io into codeigniter app we need to use NPM command. NPM is a package manager for Node modules.

To install socket.io and express server open command prompt and go to the root project directory of your codeigniter app and use below command.

To install express:


$ npm install express --save

To install socket.IO:


$ npm install socket.io --save

Setup in Codeigniter:

Below is the simple steps to get setup with codeigniter. In this example we are going to implement a simple real time message notification system.Lets start.

  1. Create a file named server.js inside your codeigniter root folder.Please find below the code.
var socket = require( 'socket.io' );
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
socket.on( 'new_message', function( data ) {
io.sockets.emit( 'new_message', {
message: data.message,
date: data.date,
msgcount: data.msgcount
});
});
});
2. Next, Create a view file named message.php inside application/views. Here will write all ajax process and socket emit code.emit an event to all connected sockets.
Please find below the code for view.
<html>
<head>
<title>Realtime Notification using Socket.IO in Codeigniter</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<style>
h3{
font-family: Verdana;
font-size: 18pt;
font-style: normal;
font-weight: bold;
color:red;
text-align: center;
}

</style>
<h3>Realtime Notification using Socket.IO in Codeigniter</h3>

<?php echo form_open('message/send',array('name'=>'message','method'=>'post')); ?>

<div class="container">
<divstyle="float:right;"><p><h4>Messages: <b><spanid="msgcount"></span></b></h4></p></div>
<divclass="col-md-3">
<p><inputtype="text"placeholder="Type Here..."class="form-control"size="20px"id="message"name="message" /></p>
</div>
<divclass="col-md-3"><inputtype="button"class="btn btn-primary"id="send"name="send"value="Send"/></div>
<divclass="col-md-3"></div>
<divclass="col-md-3"></div>
<tableclass="table">
<thead>
<tr>
<th>Date</th>
<th>Message</th>
</tr>
</thead>
<tbodyid="message-tbody">
<?phpforeach($allMsgs as $row){ ?>
<tr><td><?php echo $row['date']; ?></td><td><?php echo $row['msg']; ?></td></tr>
<?php } ?>
</tbody>
</table>
</div>

<?php echo form_close();?>

<scriptsrc="<?php echo base_url('assets/js/jquery-1.11.2.min.js');?>"></script>
<scriptsrc="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
<script src="<?php echo base_url('node_modules/socket.io/node_modules/socket.io-client/socket.io.js');?>"></script>
<script>
$(document).ready(function(){
$(document).on("click","#send",function() {
var dataString = {
message : $("#message").val()
};

$.ajax({
type: "POST",
url: "<?php echo base_url('message/send');?>",
data: dataString,
dataType: "json",
cache : false,
success: function(data){

if(data.success ==true){
var socket = io.connect( 'http://'+window.location.hostname+':3000' );
socket.emit('new_message', {
message: data.message,
date: data.date,
msgcount: data.msgcount
});
}
} ,error: function(xhr, status, error) {
alert(error);
},
});
});
});
var socket = io.connect( 'http://'+window.location.hostname+':3000' );
socket.on( 'new_message', function( data ) {
$("#message-tbody").prepend('<tr><td>'+data.date+'</td><td>'+data.message+'</td></tr>');
$("#msgcount").text(data.msgcount);
});
</script>
</body>
</html>

 

3. Create controller called SendController.php inside application/controllers.Here we gonna count messages and take all required data from database. Here is the code for controller.
SendController.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class SendController extends CI_Controller {
    public function index(){
        $data = array();
        $allmsgs = $this->db->select('*')->from('tbl_msg')->get()->result_array();
        $data['allMsgs'] = $allmsgs;
        $this->load->view('message',$data);
    }
    public function send(){
        $arr['msg'] = $this->input->post('message');
        $arr['date'] = date('Y-m-d');
        $arr['status'] = 1;
        $this->db->insert('tbl_msg',$arr);
        $detail = $this->db->select('*')->from('tbl_msg')->where('id',$this->db->insert_id())->get()->row();
        $msgCount = $this->db->select('*')->from('tbl_msg')->get()->num_rows();
        $arr['message'] = $detail->msg;
        $arr['date'] = date('m-d-Y', strtotime($detail->date));
        $arr['msgcount'] = $msgCount;
        $arr['success'] = true;
        echo json_encode($arr);
    }
}
4. Here is the routes configuration.
$route['default_controller'] = 'SendController';
$route['message/send'] = 'sendcontroller/send';
Now, you need to test it. Before start, you need to start server by executing below command from project root folder.
$ node server.js
Realtime Notification Example

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!

 

 

 

 

I am Hitesh from Jamshedpur (India). I have been working as a Web Application Developer from last 4+ years. I love diverse and attention catching web presence for a variety of users. Also I love to learn new things in Web Development.

Tags: , , , , , , , , ,