0% found this document useful (0 votes)
40 views21 pages

Socket.IO Chat Application Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views21 pages

Socket.IO Chat Application Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Socket.

IO
Problems faced by traditional HTTP
requests
• Unidirectional communication: HTTP is inherently a request-response protocol, where the
client sends a request to the server, and the server responds. This model doesn't support
real-time updates initiated by the server without the client explicitly requesting them.

• Polling: One approach to achieve real-time updates with HTTP is through polling, where the
client repeatedly sends requests to the server at regular intervals to check for updates. This
method can be inefficient, leading to unnecessary network traffic and increased server load,
especially if updates are infrequent.

• Latency: Even with polling, there's often a delay between when an event occurs on the
server and when the client receives the update. This latency can degrade the user
experience, especially in applications where real-time interaction is critical.

• Scalability: Traditional HTTP communication can be challenging to scale for real-time


applications with a large number of concurrent users. Each HTTP request creates a new
connection to the server, which can strain server resources and limit scalability.
What is [Link]?
[Link] is a library that enables
low-latency, bidirectional and
event-based communication
between a client and a server.
[Link] enables bidirectional
communication between clients and
servers. Unlike traditional HTTP requests,
where communication is initiated by the
client, [Link] allows servers to send
updates to clients without waiting for a
request. This bidirectional capability is
essential for real-time applications like chat
rooms, online gaming, and collaborative
editing
Install [Link]

npm install [Link]


Importing Required Modules

const express = require('express');


const socketIO = require('[Link]');
const path = require('path');
Creating Express App and Starting
Server
const app = express();
const server = [Link](3000, () => {
[Link]('Server is running on port
3000');
});

The server variable holds the server instance


returned by calling [Link]()
const io = socketIO(server);

// Serve static files from the 'public'


directory
[Link]([Link]([Link](__dirname,
'public')));

It creates a [Link] instance attached to the


Express server.
and serves static files (like HTML, CSS,
JavaScript) located in the 'public' directory.
[Link]('connection', socket => {
[Link]('A user connected');

// Listen for 'chat message' events from clients


[Link]('chat message', msg => {
// Broadcast the message to all clients in the same
room
[Link]('chat message', msg);
});

[Link]('disconnect', () => {
[Link]('A user disconnected');
});
});
• It listens for a 'connection' event when a client
connects via [Link].
• Upon connection, it logs a message to the
console.
• It sets up event listeners for the 'chat message'
event from clients.
• When it receives a 'chat message' event from a
client, it broadcasts the message to all connected
clients.
• It also listens for a 'disconnect' event, which
triggers when a client disconnects, and logs a
message to the console.
Now, let’s make a basic client-side
chat interface
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>[Link] Chat</title>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input"/><button>Send</button>
</form>
<script src="/[Link]/[Link]"></script>
<script>
const socket = io();

const form = [Link]('form');


const input =
[Link]('input’);

Initial script tag includes the [Link] client


library, allowing the client-side JavaScript to
connect to the [Link] server
a [Link] client instance is initialized and
assigned to the socket constant
[Link]('submit', e => {
[Link]();
if ([Link]) {
// Emit 'chat message' event with the input value
[Link]('chat message', [Link]);
[Link] = '';
}
});

This adds a submit event listener to the form. When the form is
submitted (e.g., by clicking the send button or pressing Enter),
this function executes.
[Link]();: This prevents the default form submission
behavior, which would cause the page to reload
// Listen for 'chat message' events from the server
[Link]('chat message', msg => {
const item = [Link]('li');
[Link] = msg;
[Link]('messages').appendChild(item);
});
</script>
</body>
</html>

This sets up a listener for 'chat message' events from the server.
When the client receives a message from the server, this function
executes
Test your Knowledge
Write a simple [Link] chat application where multiple users
can connect and exchange messages in real-time. The
application should have the following features:

• Display a chat interface where users can see all the messages
sent by other users.
• Allow users to enter their name when they join the chat.
• Display the names of users along with their messages.
• Implement a feature to notify all users when a new user joins
or leaves the chat.
• Ensure that the chat interface scrolls automatically to show
the latest messages.
const express = require('express');
const socketIO = require('[Link]');
const path=require('path');

const app = express();


const server = [Link](3000,()=>{
[Link]("Server started on port 3000");
});

const io = socketIO(server);

[Link]('/', (req, res) => {


[Link]([Link](__dirname, 'public', '[Link]'));
});
[Link]('connection', socket => {
[Link]('A user connected');

// Listen for 'join' event when a new user joins


[Link]('join', username => {
[Link] = username;
[Link]('chat message', { type: 'notification', message: `${username} has joined the chat`
});
});

// Listen for 'chat message' events from clients


[Link]('chat message', msg => {
[Link]('chat message', { type: 'message', username: [Link], message: msg });
});

// Listen for 'disconnect' event when a user leaves


[Link]('disconnect', () => {
[Link]('A user disconnected');
if ([Link]) {
[Link]('chat message', { type: 'notification', message: `${[Link]} has left
the chat` });
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>[Link] Chat</title>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off"
/><button>Send</button>
</form>
<script src="/[Link]/[Link]"></script>
<script>
const socket = io();

const form = [Link]('form');


const input = [Link]('input');
const messages = [Link]('messages');

[Link]('submit', e => {
[Link]();
if ([Link]) {
[Link]('chat message', [Link]);
[Link] = '';
}
});
// Prompt the user to enter their name
const username = prompt('Please enter your name:');
[Link]('join', username);

[Link]('chat message', data => {


const item = [Link]('li');
if ([Link] === 'notification') {
[Link] = [Link];
[Link] = 'bold';
} else {
[Link] = `${[Link]}: ${[Link]}`;
}
[Link](item);
// Scroll to the bottom of the chat window
[Link] = [Link];
});
</script>
</body>
</html>

You might also like