PROGRAM TO IMPLEMENT WEBCHAT APPLICATION
AIM:
To implement
a chat program that can be used over the web.
PROCEDURE:
Step 1: Install
the requirements
·
Nodejs (v 0.10.40)
·
Socketio (v 1.2.0)
·
Expressjs (v 4.10.2)
Step 2:
Create a folder / directory for the project
Step 3: Create
a file called package.json to enter the metadata of the node application
Step 4:
Create a index.html file with a form (a textarea to type message, a button to
send, a section to display
the message)
Step 5:
Create a index.js file to handle the events from clients and broadcast the
messages to all the clients
connected through socketio javascript.
Step 6: Create
a folder named assets and download jquery.js file inside that folder.
Step 7:
Install expressjs & socketjs using npm (which comes by default with nodejs)
Step 8:
Start the nodejs server by invoking node index.js file. Application will be
started and listening on port
number 3000 (as configured in the js file).
Step 9:
Open two tabs in your browser and visit (http://localhost:3000) in both the tabs and you should be able to send and receive
messages between the two.
File
1 – package.json
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket io app",
"dependencies": {
"express": "^4.10.2",
"socket.io": "~1.3.7"
}
}
File
2 – index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
*
{ margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0;
width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none;
padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off"
/><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="/assets/jquery.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>
File
3 – index.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use('/assets', express.static(__dirname +
'/assets'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Output
(Screenshots):
Open web browser with 2 tabs
and navigate to localhost:3000 in both