Socket.io

Socket.IO enables real-time bidirectional event-based communication.
It works on every platform, browser or device, focusing equally on reliability and speed.

Example 1 chats with express

app.js


var express = require('express'),
app = express(),
http = require('http').createServer(app),
io = require('socket.io')(http);

http.listen(3000);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
});

io.on('connection', function (client) {
console.log('client connected..');
client.on('send message', function (data) {
console.log(data);
client.emit('new message',data);
client.broadcast.emit('new message', data);
});
});

index.html

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Chating using socket.io</title>
<style type="text/css">
#chats{
height: 500px;
}
</style>
</head>
<body>

<div id="chats"></div>
<form id="frm-chat">
<input type="text" id="message"/>
<input type="submit">
</form>


<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function ($) {
var socket = io.connect('http://localhost:3000');
var $chats = $("#chats");
var $frm = $("#frm-chat");
var $message = $("#message");
$frm.submit(function (e) {
e.preventDefault();
socket.emit('send message', $message.val());
$message.val('');
});
socket.on('new message', function (data) {
$chats.append(data + "<br />");
});
});

</script>
</body>
</html>

oke lets try the console like this following :

$ node app.js

and then open with your browser with url : http://localhost:3000

 

Example 2 chats with private message "/w username message" and bootstrap

app.js

var app = require('express')(),
server = require('http').createServer(app),
io = require('socket.io')(server),
users = {};
server.listen(3000);

app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (client) {
console.log('connected');
client.on('new user', function (data, callback) {
if (data in users) {
callback(false);
} else {
console.log(data);
callback(true);
client.nickname = data;
users[client.nickname] = client;
updateUser();
}
});

function updateUser() {
client.emit('usernames', Object.keys(users));
client.broadcast.emit('usernames', Object.keys(users));
}

client.on('send message', function (data, callback) {
var msg = data.trim();
if (msg.substr(0, 3) === '/w ') {
msg = msg.substring(3);
var ind = msg.indexOf(' ');
if (ind !== -1) {
var name = msg.substring(0, ind);
var msg = msg.substring(ind + 1);
if (name in users) {
users[name].emit('whisper', {msg: msg, nickname: client.nickname});
console.log('whisper');
} else {
callback('Error! Enter a valid user!')
}
} else {
callback('Error! Please enter your message');
}
} else {
client.emit('new message', {msg: msg, nickname: client.nickname});
client.broadcast.emit('new message', {msg: msg, nickname: client.nickname});
}
});

client.on('disconnect', function (data) {
if (!client.nickname) return;
console.log('users :' + client.nickname + 'has left');
delete users[client.nickname];
updateUser();
});
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.io with private message</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="page-header">
<h2>Chats</h2>
</div>
<div id="div-user">
<form class="form-inline" id="form-user">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Your username">
<span class="help-block" id="usernameError"></span>
</div>

<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>

<div id="wrap" style="display: none">
<div class="row">
<div class="col-md-5">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title" id="panel-title">Chats:</h3>
</div>
<div class="panel-body" id="chats"></div>
</div>
</div>
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Users:</h3>
</div>
<div class="panel-body" id="users"></div>
</div>
</div>
</div>

<div class="row">
<div class="col-md-6">
<form id="form-message" class="form-horizontal" role="form">
<div class="input-group">
<span class="input-group-addon" id="user-addon"></span>
<input type="text" class="form-control" id="message" placeholder="your message">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Go!</button>
</span>
</div>
</form>
</div>
</div>

</div>

</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function ($) {
var socket = io.connect('http://localhost:3000'),
$divUser = $("#div-user"),
$chats = $("#chats"),
$users = $("#users"),
$formUser = $("#form-user"),
$username = $("#username"),
$usernameError = $("#usernameError"),
$wrap = $("#wrap"),
$formMessage = $("#form-message"),
$message = $("#message"),
$useraddon = $("#user-addon");

//submit form user
$formUser.submit(function (e) {
e.preventDefault();
socket.emit('new user', $username.val(), function (data) {
if (data) {
$wrap.show();
$divUser.hide();
$useraddon.html($username.val());
} else {
$username.closest("form").addClass("has-error");
$usernameError.html("Error, username already have been taken, please try again");
}
});
});
//wait event on usernames
socket.on('usernames', function (data) {
var html = '';
for (i = 0; i < data.length; i++) {
html += data[i] + "<br />";
}
$users.html(html);
});

$formMessage.submit(function (e) {
e.preventDefault();
socket.emit('send message', $message.val(), function (data) {
// your stuff here
});
$message.val('');
});
socket.on('new message', function (data) {
$chats.append(data.nickname + ": " + data.msg + "<br />");
});
socket.on('whisper', function (data) {
$chats.append(data.nickname + ": " + data.msg + "<br />");
});
});
</script>

</body>
</html>

oke lets try the console like this following :

$ node app.js

and then open with your browser with url : http://localhost:3000

 

Example 3 chats with mongodb

lib/chat-db.js

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/chat', function (err) {
if (err) {
console.log(err);
} else {
console.log('connect to mongodb');
}
});


var ChatSchema = mongoose.Schema({
nickname: String,
msg: String,
createdAt: {type: Date, default: Date.now}
});

var Chat = mongoose.model('Message', ChatSchema);

exports.getMessages = function (limit, cb) {
var query = Chat.find({});
query.sort('-createdAt').limit(limit).exec(function (err, docs) {
cb(err, docs);
});
}

exports.saveMessage = function (data, cb) {
var newChat = new Chat({msg: data.msg, nickname: data.nickname});
newChat.save(function (err) {
if (err) {
cb(err);
}
});
}

 

 app.js


var app = require('express')(),
server = require('http').createServer(app),
mongoose = require('mongoose'),
io = require('socket.io')(server),
chat = require('./lib/chat-db'),
users = {};
server.listen(3000);


app.get('/', function (req, res) {
res.sendFile(__dirname + '/socket9.html');
});

io.on('connection', function (client) {
chat.getMessages(20, function (err, docs) {
return client.emit('get messages', docs);
});
client.on('new user', function (data, callback) {
if (data in users) {
callback(false);
} else {
console.log(data);
callback(true);
chat.getMessages(10, callback);
client.nickname = data;
users[client.nickname] = client;
updateUser();
}
});

function updateUser() {
client.emit('usernames', Object.keys(users));
client.broadcast.emit('usernames', Object.keys(users));
}

client.on('send message', function (data, callback) {
var msg = data.trim();
if (msg.substr(0, 3) === '/w ') {
msg = msg.substring(3);
var ind = msg.indexOf(' ');
if (ind !== -1) {
var name = msg.substring(0, ind);
var msg = msg.substring(ind + 1);
if (name in users) {
users[name].emit('whisper', {msg: msg, nickname: client.nickname});
console.log('whisper');
} else {
callback('Error! Enter a valid user!')
}
} else {
callback('Error! Please enter your message');
}
} else {
chat.saveMessage({msg: msg, nickname: client.nickname}, function (err) {
if (err) throw err;
});
client.emit('new message', {msg: msg, nickname: client.nickname});
client.broadcast.emit('new message', {msg: msg, nickname: client.nickname});
}
});

client.on('disconnect', function (data) {
if (!client.nickname) return;
console.log('users :' + client.nickname + 'has left');
delete users[client.nickname];
updateUser();
});
});

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.io with private message</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="page-header">
<h2>Chats</h2>
</div>
<div id="div-user">
<form class="form-inline" id="form-user">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Your username">
<span class="help-block" id="usernameError"></span>
</div>

<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>

<div id="wrap" style="display: none">
<div class="row">
<div class="col-md-5">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title" id="panel-title">Chats:</h3>
</div>
<div class="panel-body" id="chats"></div>
</div>
</div>
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Users:</h3>
</div>
<div class="panel-body" id="users"></div>
</div>
</div>
</div>

<div class="row">
<div class="col-md-6">
<form id="form-message" class="form-horizontal" role="form">
<div class="input-group">
<span class="input-group-addon" id="user-addon"></span>
<input type="text" class="form-control" id="message" placeholder="your message">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Go!</button>
</span>
</div>
</form>
</div>
</div>

</div>

</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function ($) {
var socket = io.connect('http://localhost:3333'),
$divUser = $("#div-user"),
$chats = $("#chats"),
$users = $("#users"),
$formUser = $("#form-user"),
$username = $("#username"),
$usernameError = $("#usernameError"),
$wrap = $("#wrap"),
$formMessage = $("#form-message"),
$message = $("#message"),
$useraddon = $("#user-addon");

//submit form user
$formUser.submit(function (e) {
e.preventDefault();
socket.emit('new user', $username.val(), function (data) {
if (data) {
$wrap.show();
$divUser.hide();
$useraddon.html($username.val());
} else {
$username.closest("form").addClass("has-error");
$usernameError.html("Error, username already have been taken, please try again");
}
});
});
//wait event on usernames
socket.on('usernames', function (data) {
var html = '';
for (i = 0; i < data.length; i++) {
html += data[i] + "<br />";
}
$users.html(html);
});

socket.on('get messages', function (data) {
for (var i = 0; i < data.length; i++) {
displayMessages(data[i]);
}
});

function displayMessages(data){
$chats.append(data.nickname + ": " + data.msg + "<br />");
}

$formMessage.submit(function (e) {
e.preventDefault();
socket.emit('send message', $message.val(), function (data) {
// your stuff here
});
$message.val('');
});
socket.on('new message', function (data) {
displayMessages(data);
});
socket.on('whisper', function (data) {
displayMessages(data);
});
});
</script>

</body>
</html>

 

Leave a Comment:


108594513142170714601 2 months ago

this blog providing good information To learn NodeJS visit http://iwebworld.info  contact: iwebworldinfo@gmail.com



108594513142170714601 2 months ago

this blog providing good information To learn NodeJS visit http://iwebworld.info  contact: iwebworldinfo@gmail.com



108594513142170714601 2 months ago

this blog providing good information To learn NodeJS visit http://iwebworld.info  contact: iwebworldinfo@gmail.com



108594513142170714601 2 months ago

this blog providing good information To learn NodeJS visit http://iwebworld.info  contact: iwebworldinfo@gmail.com



108594513142170714601 2 months ago

this blog providing good information To learn NodeJS visit http://iwebworld.info  contact: iwebworldinfo@gmail.com




digital_ocean