You are on page 1of 58

A Project Report

On
Online Public Chat Rooms
605: Major Project Work
By
Aditya Pratap Singh
(Roll No: - 180732106003)
Project report submitted in partial fulfillment of the requirements
For the award of the degree of
“Bachelor of Computer application”
Session (2018-2021)
Under the guidance of
MR. VEENESH SHROTRIYA
(Assistant Professor of Computer Science Department)

Department of Computer Science,


Prince Institute of Innovative Technology (PIIT),
(Affiliated to CCS University, Meerut)

PRINCE INSTTUTE OF INNOVATIVE TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE
CERTIFICATE
This is to certify that the project report entitled Online Public Chat Room
being submitted by Aditya Pratap Singh (Roll No: - 180732106003), in
partial fulfillment for the award of the Degree of Bachelor of Computer
Science to the Chaudhary Charan Singh University is a record of Bonafede
work carried out by them infer my guidance and supervision.
The result embodied in this project report have not been submitted to any
other University or Institute for the award of any Degree or dioploma.

Internal Guide Head of the Department


Veenesh Shrotriya Veenesh Shrotriya
Assistant Professor, CS Professor, CS

External Examiner
ACKNOWLEDGMENT

We wish to express our gratitude to our parents and our teachers and our
Head of the Department, Veenesh Shrotriya, who gave us full support to
finish the project work successfully.
We wish to express our grateful thank to our project guide Veenesh
Shrotriya , Assistant Professor of CS Department who gave us full
support and her constant encouragement, valuable suggestion and helping
tendency which has make us to carry out and finish the project work
successfully
Our thanks to all other faculty and non-teaching staff members of our
department for their support and pees for having stood by us and helped us
to complete this project

PROJECT ASSOCIATE
ADITYA PRATAP SINGH
(Roll No: - 180732106003)
INDEX

1) Online Public Chat Rooms (Detailed Overview)

2) System Requirements.

3) Tools and Frameworks used in this project.

4) Dependencies used in this project.

5) Some images to describe working of chat application.

6) Project Structure.

7) Data Flow Diagram.

8) Coding.

9) Conclusion.

10) Bibliography.
Online Public Chat Rooms

The term chat room, or chatroom (and sometimes group chat;


abbreviated as GC), is primarily used to describe any form of synchronous
conferencing, occasionally even asynchronous conferencing. The term can
thus mean any technology ranging from real-time online chat and online
interaction with strangers (e.g., online forums) to fully immersive graphical
social environments.
The primary use of a chat room is to share information via text with a group
of other users. Generally speaking, the ability to converse with multiple
people in the same conversation differentiates chat rooms from instant
messaging programs, which are more typically designed for one-to-one
communication. The users in a particular chat room are generally connected
via a shared internet or other similar connection, and chat rooms exist
catering for a wide range of subjects. New technology has enabled the use
of file sharing and webcams to be included in some programs. This would
be considered a chat room.
1)-History : The first chat system was used by the U.S. government in
1971. It was developed by Murray Turoff, a young PhD graduate from
Berkeley, and its first use was during President Nixon's wage-price freeze
under Project Delphi. The system was called EMISARI and would allow 10
regional offices to link together in a real-time online chat known as the party
line. It was in use up until 1986. The first public online chat system was
called Talkomatic, created by Doug Brown and David R. Woolley in 1973 on
the PLATO System at the University of Illinois. It offered several channels,
each of which could accommodate up to five people, with messages
appearing on all users' screens character-by-character as they were typed.
Talkomatic was very popular among PLATO users into the mid-1980s. In
2014 Brown and Woolley released a web-based version of Talkomatic.
Galaxy, eMule, Filetopia, Retroshare, Vuze, WASTE, WinMX, etc. Many
popular social media platforms are now used as chat The first dedicated
online chat service that was widely available to the public was the
CompuServe CB Simulator in 1980, created by CompuServe executive
Alexander "Sandy" Trevor in Columbus, Ohio. Chat rooms gained
mainstream popularity with AOL.
Jarkko Oikarinen created Internet Relay Chat (IRC) in 1988. Many peer-to-
peer clients have chat rooms, e.g. Ares rooms, such as WhatsApp,
Facebook Groups, Twitter, and TikTok.

2)-Graphical multi-user environments: Visual chat rooms add


graphics to the chat experience, in either 2D or 3D (employing virtual
reality technology). These are characterized by using a graphic
representation of the user, an avatar (virtual elements such as games (in
particular massively multiplayer online games) and educational material
most often developed by individual site owners, who in general are simply
more advanced users of the systems. The most popular environments, such
as The Palace, also allow users to create or build their own spaces. Some
of the most popular 3D chat experiences are IMVU and Second Life (though
they extend far beyond just chat). Many such implementations generate
profit by selling virtual goods to users at a high margin.
Some online chat rooms also incorporate audio and video communications,
so that users may actually see and hear each other.

3)-Games: Games are also often played in chat rooms. These are
typically implemented by an external process such as an IRC bot joining the
room to conduct the game. Trivia question & answer games are most
prevalent. A historic example is Hunt the Wumpus. Chatroom-based
implementations of the party game Mafia also exist. A similar but more
complex style of text-based gaming are MUDs, in which players interact
within a textual, interactive fiction–like environment.

4)-Rules of behavior: Chat rooms, particularly those intended for


children, usually have rules that they require users to follow. The rules are
generally posted before entry, either on a web page or an MOTD-type
banner in the case of IRC and other text-based chat systems. Rules usually
do not allow users to use offensive/rude language, or to promote hate,
violence, and other negative issues. Many also disallow impersonating
another user. Chat rooms often do not allow advertising or "flooding", which
is continually filling the screen with repetitive text. Typing with caps lock on
is usually considered shouting (suggesting anger) and is discouraged.
Offenders of these rules can be "kicked" (temporarily ejected from the room,
but allowed back in) or banned completely either on a temporary or
permanent basis.
Sometimes chat room venues are moderated either by limiting who is
allowed to speak (not common), by having comments be approved by
moderators (often presented as asking questions of a guest or celebrity), or
by having moderation volunteers patrol the venue watching for disruptive or
otherwise undesirable behavior. Yet, most commonly used chat rooms are
not moderated and users may chat freely with the other occupants of the
room.

6)-Social criticism: Criticism of online chatting and text


messaging include concern that they replace proper English
with shorthand or with an almost completely new hybrid language.
Writing is changing as it takes on some of the functions and features of
speech. Internet chat rooms and rapid real-time teleconferencing allow
users to interact with whoever happens to coexist in cyberspace. These
virtual interactions involve us in 'talking' more freely and more widely than
ever before.[15] With chatrooms replacing many face-to-face conversations, it
is necessary to be able to have quick conversation as if the person were
present, so many people learn to type as quickly as they would normally
speak. Some critics[who?] are wary that this casual form of speech is being
used so much that it will slowly take over common grammar; however, such
a change has yet to be seen.
With the increasing population of online chatrooms there has been a
massive growth of new words created or slang words, many of them
documented on the website Urban Dictionary. Sven Birkerts wrote:
"as new electronic modes of communication provoke similar anxieties
amongst critics who express concern that young people are at risk,
endangered by a rising tide of information over which the traditional controls
of print media and the guardians of knowledge have no control on it".
In Guy Merchant's journal article Teenagers in Cyberspace: An Investigation
of Language Use and Language Change in Internet Chatrooms; Merchant
says
"that teenagers and young people are in the leading the movement of
change as they take advantage of the possibilities of digital technology,
drastically changing the face of literacy in a variety of media through their
uses of mobile phone text messages, e-mails, web-pages and on-line
chatrooms. This new literacy develops skills that may well be important to
the labor market but are currently viewed with suspicion in the media and by
educationalists.
Merchant also says "Younger people tend to be more adaptable than other
sectors of society and, in general, quicker to adapt to new technology. To
some extent they are the innovators, the forces of change in the new
communication landscape." In this article he is saying that young people are
merely adapting to what they were given.

Features Of This Online Public Chat Rooms:


Like any other chatting application, this application can also be used
for chatting and communicating with friends and family, but unlike other
applications this application has some unique and advanced features like:
 We can easily create a group chat while in the rooms, we can invite
as many as people in one room and they all can chat simultaneously
with each other at the same time.
 One user can create as many as rooms as he wants.
 Login does not required id and password, as it is a public chat
rooms, anyone with room id can enter in a room.
 Whenever a user joins the chat, system welcomes him with a
welcome message and system also notifies other participants about
joining of new user.
 Whenever a user left the chat, it notifies other users about leaving of
that participant.
 It did also show all the active users of a room.
 No two users can have a same user name in a same room.
 It also has built-in emoji support.
 It has a brilliant and fantastic user interface which is also easy to use
and pleasant to look.
System Requirements

 4 GB Ram.

 256 GB Hard Disk.

 2 Ghz Pentium Processor or above.

 Node Js Installed.

 Git Installed.

 Active Internet Connection.


Tools and Framework used in this project

1). React JS: React.js is an open-source JavaScript library that is used


for building user interfaces specifically for single-page applications. It’s used
for handling the view layer for web and mobile apps. React also allows us to
create reusable UI components. React was first created by Jordan Walke, a
software engineer working for Facebook. React first deployed on
Facebook’s newsfeed in 2011 and on Instagram.com in 2012.
React allows developers to create large web applications that can change
data, without reloading the page. The main purpose of React is to be fast,
scalable, and simple. It works only on user interfaces in the application. This
corresponds to the view in the MVC template. It can be used with a
combination of other JavaScript libraries or frameworks, such as Angular JS
in MVC.
React JS is also called simply to React or React.js. 

 What are the React.js Features?

Let us take a closer look at some important features of React.  


React.js properties includes the following:
 React.js is declarative
 React.js is simple
 React.js is component based
 React.js supports server side
 React.js is extensive
 React.js is fast 
 React.js is easy to learn
 JSX: In React, instead of using regular JavaScript for templating, it
uses JSX. JSX is a simple JavaScript that allows HTML quoting and
uses these HTML tag syntax to render subcomponents. HTML syntax
is processed into JavaScript calls of React Framework. We can also
write in pure old JavaScript.
  

 
 React Native: React has native libraries that were announced by
Facebook in 2015, which provides the react architecture to native
applications like IOS, Android and UPD. 
React-native is a mobile apps building framework using only
Javascript. It uses the same design as React, letting you utilize/include
a rich mobile UI library/ declarative components. It uses the same
fundamental UI building blocks as regular iOS and Android apps. The
best part of using react-native is to allow/adopt components written in
Objective-C, Java, or Swift.
 
 
 Single-Way data flow: In React, a set of immutable values are
passed to the components renderer as properties in its HTML tags.
The component cannot directly modify any properties but can pass a
call back function with the help of which we can do modifications. This
complete process is known as “properties flow down; actions flow up”.
 

 
 Virtual Document Object Model: React creates an in-memory
data structure cache which computes the changes made and then
updates the browser. This allows a special feature that enables the
programmer to code as if the whole page is rendered on each change
whereas react library only renders components that actually change.

Why React?
Now, the main question arises in front of us is why one should use
React. There are so many open-source platforms for making the front-end
web application development easier, like Angular. Let us take a quick look
on the benefits of React over other competitive technologies or frameworks.
With the front-end world-changing on a daily basis, it’s hard to devote time
to learning a new framework – especially when that framework could
ultimately become a dead end. So, if you're looking for the next best thing
but you're feeling a little bit lost in the framework jungle, I suggest checking
out React.
 
1) Simplicity: ReactJS is just simpler to grasp right away. The
component-based approach, well-defined lifecycle, and use of just
plain JavaScript make React very simple to learn, build a professional
web (and mobile applications), and support it. React uses a special
syntax called JSX which allows you to mix HTML with JavaScript.
This is not a requirement; Developer can still write in plain JavaScript
but JSX is much easier to use.
 
2) Easy to learn: Anyone with a basic previous knowledge in
programming can easily understand React while Angular and Ember
are referred to as ‘Domain-specific Language’, implying that it is
difficult to learn them. To react, you just need basic knowledge of
CSS and HTML.

3) Native Approach: React can be used to create mobile


applications (React Native). And React is a diehard fan of reusability,
meaning extensive code reusability is supported. So at the same
time, we can make IOS, Android and Web applications.
 
4) Data Binding: React uses one-way data binding and an application
architecture called Flux controls the flow of data to components
through one control point – the dispatcher. It's easier to debug self-
contained components of large ReactJS apps.
 
5) Performance: React does not offer any concept of a built-in
container for dependency. You can use Browserify, Require JS,
EcmaScript 6 modules which we can use via Babel, ReactJS-di to
inject dependencies automatically.
 
6) Testability: ReactJS applications are super easy to test. React
views can be treated as functions of the state, so we can manipulate
with the state we pass to the ReactJS view and take a look at the
output and triggered actions, events, functions, etc. 

What are the weaknesses of ReactJS?


We’ve spoken a lot about the benefits of ReactJS and why you would
want to use it, but we haven’t mentioned any drawbacks. In order for us to
determine when React is the right technical choice, it’s important to
understand when it’s not.
As we’ve already covered, React is a powerful tool that can help you build
complex user interfaces. However, it’s important to remember that JavaScript
with no framework can often get you really far too. If it’s a simple task that
you can do with 2 lines of JavaScript, does it make sense to go through the
whole effort of understanding all the fragments to use React? Probably not.
Not every problem will require a tool as powerful as React, and when
assessing our options, we should think, “are we using a rocket ship to travel
next door?”.
So, how can we actually determine when we’re using a rocket ship to travel
next door? As a general rule of thumb, if there’s a lot of interaction and “stuff”
taking place between the component and other areas of the site, then React
would most likely be a good choice. Put another way, if your user interface
(form fields, HTML, and JavaScript) is complicated and needs structure, then
React will simplify things and allow you to scale. If it’s not, then JavaScript
with no framework may be sufficient for you.
It takes a good amount of work to set up React (as we know). If your project
doesn’t cross the threshold for needing a toolkit/framework, you probably
shouldn’t use React.
2). Node JS:  Node.js is an open-source and cross-platform runtime
environment for executing JavaScript code outside a browser. You need to
remember that NodeJS is not a framework and it’s not a programming
language. Most people are confused and understand it’s a framework or a
programming language. We often use Node.js for building back-end
services like APIs like Web App or Mobile App. It’s used in production by
large companies such as Paypal, Uber, Netflix, Walmart, and so on.

Features of Node JS: 


There are other programming languages also which we can use to build
back-end services so what makes Node.js different I am going to explain.
 It’s easy to get started and can be used for prototyping and agile
development
 It provides fast and highly scalable services
 It uses JavaScript everywhere, so it’s easy for a JavaScript
programmer to build back-end services using Node.js
 Source code cleaner and consistent.
 Large ecosystem for open source library.
 It has Asynchronous or Non-blocking nature.

Advantages of Node JS: 


Here are the benefits of using Node.js 
1) Easy Scalability: Developers prefer to use Node.js because it is
easily scaling the application in both horizontal and vertical
directions. We can also add extra resources during the scalability of
the application.
2) Real-time web apps: If you are building a web app you can also
use PHP, and it will take the same amount of time when you use
Node.js, But if I am talking about building chat apps or gaming apps
Node.js is much more preferable because of faster synchronization.
Also, the event loop avoids HTTP overloaded for Node.js
development.
3) Fast Suite: NodeJs runs on the V8 engine developed by Google.
Event loop in NodeJs handles all asynchronous operation so
NodeJs acts like a fast suite and all the operations can be done
quickly like reading or writing in the database, network connection,
or file system
4) Easy to learn and code:  NodeJs is easy to learn and code
because it uses JavaScript. If you are a front-end developer and
have a good grasp of JavaScript you can easily learn and build the
application on NodeJS
5) Advantage of Caching: It provides the caching of a single
module. Whenever there is any request for the first module, it gets
cached in the application memory, so you don’t need to re-execute
the code.
6) Data Streaming: In NodeJs HTTP request and response are
considered as two separate events. They are data stream so when
you process a file at the time of loading it will reduce the overall time
and will make it faster when the data is presented in the form of
transmissions. It also allows you to stream audio and video files at
lightning speed.
7) Hosting: PaaS (Platform as a Service) and Heroku are the hosting
platforms for NodeJS application deployment which is easy to use
without facing any issue.
8) Corporate Support: Most of the well-known companies like
Walmart, Paypal, Microsoft, Yahoo are using NodeJS for building
the applications. NodeJS uses JavaScript, so most of the companies
are combining front-end and backend Teams together into a single
unit.

Application of Node JS:


 Node JS should be preferred to build:
 Real-Time Chats,
 Complex Single-Page applications,
 Real-time collaboration tools,
 Streaming apps
 JSON APIs based application
Node.js Disadvantages: What is Node.js not good for
 Reduces performance when handling Heavy Computing Tasks.
 Node.js invites a lot of code changes due to Unstable API.
 Node.js Asynchronous Programming Model makes it difficult to
maintain code.
 Choose Wisely – Lack of Library Support can Endanger your Code.
 High demand with a few Experienced Node.js Developers.
3). Socket IO: Socket.IO is a JavaScript library for real-time web
applications. It enables real-time, bi-directional communication between web
clients and servers. It has two parts: a client-side library that runs in the
browser, and a server-side library for node.js. Both components have an
identical API.

Real-time applications:
A real-time application (RTA) is an application that functions within a period
that the user senses as immediate or current.
Some examples of real-time applications are −
Instant messengers − Chat apps like Whatsapp, Facebook Messenger,
etc. You need not refresh your app/website to receive new messages.
Push Notifications − When someone tags you in a picture on Facebook,
you receive a notification instantly.
Collaboration Applications − Apps like google docs, which allow multiple
people to update same documents simultaneously and apply changes to all
people's instances.
Online Gaming − Games like Counter Strike, Call of Duty, etc., are also
some examples of real-time applications.
Why Socket.IO?
Writing a real-time application with popular web applications stacks like
LAMP (PHP) has traditionally been very hard. It involves polling the server
for changes, keeping track of timestamps, and it is a lot slower than it
should be.
Sockets have traditionally been the solution around which most real-time
systems are architected, providing a bi-directional communication channel
between a client and a server. This means that the server can push
messages to clients. Whenever an event occurs, the idea is that the server
will get it and push it to the concerned connected clients.
Socket.IO is quite popular, it is used by Microsoft Office, Yammer,
Zendesk, Trello, and numerous other organizations to build robust real-
time systems. It one of the most powerful JavaScript
frameworks on GitHub, and most depended-upon NPM (Node Package
Manager) module. Socket.IO also has a huge community, which means
finding help is quite easy.
Dependencies used in this project

1) React Router: Routing is a process in which a user is directed to


different pages based on their action or request. ReactJS Router is
mainly used for developing Single Page Web Applications. React
Router is used to define multiple routes in the application. When a
user types a specific URL into the browser, and if this URL path
matches any 'route' inside the router file, the user will be redirected to
that particular route.
React Router is a standard library system built on top of the React
and used to create routing in the React application using React
Router Package. It provides the synchronous URL on the browser
with data that will be displayed on the web page. It maintains the
standard structure and behavior of the application and mainly used
for developing single page web applications.
2) React Scroll to Bottom: React container that will auto scroll to
bottom or top if new content is added and viewport is at the bottom,
similar to tail -f. Otherwise, a "jump to bottom" button will be shown
to allow user to quickly jump to bottom.
3) React Emoji: A library for using modern emojis in react
application.
4) Query String: A query string is a part of a uniform resource
locator (URL) that assigns values to specified parameters. A query
string commonly includes fields added to a base URL by a Web
browser or other client application, for example as part of an HTML
form.
A web server can handle a Hypertext Transfer Protocol (HTTP)
request either by reading a file from its file system based on
the URL path or by handling the request using logic that is specific to
the type of resource. In cases where special logic is invoked, the
query string will be available to that logic for use in its processing,
along with the path component of the URL.
5) Socket IO: Socket.io is a JavaScript library that enables real-time,
bi-directional and event driven communication between the client and
server. Socket.io consists of two similar APIs i.e.
A node.js server API.
A JavaScript client API which can also be run from node.js.
Socket.io uses engine.io under the hood to establish connection and
to exchange data between client and server. Engine.io is used for the
server side implementation whereas engine.io-client is used for the
client side implementation.
6) Socket IO Client: This library is used to connect to web sockets on
server from client side.
7) CORS: Cross-Origin Resource Sharing (CORS) is an HTTP-header
based mechanism that allows a server to indicate any other origins
(domain, scheme, or port) than its own from which a browser should
permit loading of resources. CORS also relies on a mechanism by
which browsers make a “preflight” request to the server hosting the
cross-origin resource, in order to check that the server will permit the
actual request. In that preflight, the browser sends headers that
indicate the HTTP method and headers that will be used in the actual
request.
8) Nodemon: nodemon is a tool that helps develop node.js based
applications by automatically restarting the node application when file
changes in the directory are detected.
Nodemon does not require any additional changes to your code or
method of development. nodemon is a replacement wrapper
for node. To use nodemon, replace the word node on the command
line when executing your script.
9) Express: Express is the most popular Node web framework, and is
the underlying library for a number of other popular Node web
frameworks. It provides mechanisms to:
Write handlers for requests with different HTTP verbs at different URL
paths (routes).
Integrate with "view" rendering engines in order to generate
responses by inserting data into templates.
Set common web application settings like the port to use for
connecting, and the location of templates that are used for rendering
the response.
Add additional request processing "middleware" at any point within
the request handling pipeline.
While Express itself is fairly minimalist, developers have created
compatible middleware packages to address almost any web
development problem. There are libraries to work with cookies,
sessions, user logins, URL parameters, POST data, security headers,
and many more. You can find a list of middleware packages
maintained by the Express team at Express Middleware (along with a
list of some popular 3rd party packages).
Some images to describe working of chat
application:

Fig 1

Fig 2
Project Structure
Data Flow Diagram
CODING ( PROGRAMMING )

 Index.js (client side):

import React from "react";


import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.querySelector("#root"));

 App.js
import React from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import Join from "./components/Join/Join";
import Chat from "./components/Chat/Chat";
const App=() => (
<Router>
<Route path="/" exact component={Join} />
<Route path="/chat" component={Chat} />
</Router>
);

export default App;

3) Chat.js:
import React, { useState, useEffect } from "react";
import queryString from "query-string";
import io from "socket.io-client";
import InfoBar from "../InfoBar/InfoBar";
import Input from "../Input/Input";
import TextContainer from "../TextContainer/TextContainer";
import Messages from "../Messages/Messages";
import "./Chat.css";

let socket;

const Chat = ({ location }) => {


const [name, setName] = useState("");
const [room, setRoom] = useState("");
const [users, setUsers] = useState("");
const [message, setMessage] = useState("");
const [messages, setMessages] = useState([]);
const ENDPOINT = "https://react-chatapp12.herokuapp.com/";

useEffect(() => {
const { name, room } = queryString.parse(location.search);

socket = io(ENDPOINT);

setName(name);
setRoom(room);
socket.emit("join", { name, room }, (error) => {
if (error) {
alert(error);
document.location = "/";
}
});
return () => {
socket.disconnect();
socket.off();
};
}, [ENDPOINT, location.search]);

useEffect(() => {
socket.on("message", (message) => {
setMessages([...messages, message]);
});
socket.on("roomData", ({ users }) => {
setUsers(users);
});
return () => {
socket.off();
};
}, [messages]);

const sendMessage = (event) => {


event.preventDefault();
if (message) {
socket.emit("sendMessage", message, () => setMessage(""));
}
};

console.log(message, messages);

return (
<div>
<div>
<TextContainer
users={users}
pageWrapId={"page-wrap"}
outerContainerId={"outer-container"}
/>
</div>
<div className="outerContainer" id="page-wrap">
<div className="container">
<InfoBar room={room} />
<Messages messages={messages} name={name} />
<Input
message={message}
setMessage={setMessage}
sendMessage={sendMessage}
/>
</div>
</div>
</div>
);
};

export default Chat;

4) InfoBar.js:
import React from "react";
import "./InfoBar.css";
import closeIcon from "../../icons/closeIcon.png";
import onlineIcon from "../../icons/onlineIcon.png";

const InfoBar = ({ room }) => (


<div className="InfoBar">
<div className="leftInnerContainer">
<img className="onlineIcon" src={onlineIcon} alt="online" />
<h3>Room {room}</h3>
</div>
<div className="rightInnerContainer">
<a href="/">
<img src={closeIcon} alt="close" />
</a>
</div>
</div>
);

export default InfoBar;

5) Input.js:
import React from 'react';
import './Input.css';

const Input = ({ message, setMessage, sendMessage }) => (


<form className="form">
<input
className="input"
type="text"
placeholder="Type a message..."
value={message}
onChange={( event ) => setMessage(event.target.value)}
onKeyPress= {event => event.key === 'Enter' ? sendMessage(event) :
null}
/>
<button className="sendButton" onClick={(event) =>
sendMessage(event) }>Send</button>

</form>
)
export default Input;

6) Join.js:
import React, {useState} from 'react';
import { Link } from 'react-router-dom';

import './Join.css';

const Join = () => {


const [name,setName] = useState('');
const [room,setRoom] = useState('');

return(
<div className="joinOuterContainer">
<div className="joinInnerContainer">
<h1 className="heading">Join</h1>
<div><input placeholder="Name" className="joinInput" type="text"
onChange={(event) => setName(event.target.value)} /></div>
<div><input placeholder="Room" className="joinInput mt-20"
type="text" onChange={(event) => setRoom(event.target.value)} /></div>
<Link onClick={event => (!name || !room) ? event.preventDefault() :
null} to={ `/chat?name=${name}&room=${room}`}>
<button className="button mt-20" type="submit">Sign
In</button>
</Link>
</div>
</div>
)
}

export default Join;

7) Messages.js:
import React from 'react';
import ScrollToBottom from 'react-scroll-to-bottom';
import Message from '../Message/Message';
import './Messages.css';

const Messages = ({ messages, name}) => (


<ScrollToBottom className="messages">
{messages.map((message, i) => <div key={i}><Message
message={message} name={name} /></div>)}
</ScrollToBottom>
)

export default Messages;

8) Message.js
import React from 'react';
import ReactEmoji from 'react-emoji';
import './Message.css';
const Message = ({ message: {user, text}, name }) => {
let isSentByCurrentUser = false;
const trimmedName = name.trim().toLowerCase();
if(user === trimmedName){
isSentByCurrentUser = true;
}

return (
isSentByCurrentUser
?(
<div className="messageContainer justifyEnd">
<p className="sentText pr-10">{trimmedName}</p>
<div className="messageBox backgroundBlue">
<p className="messageText
colorWhite">{ReactEmoji.emojify(text)}</p>
</div>
</div>
)
:(
<div className="messageContainer justifyStart">

<div className="messageBox backgroundLight">


<p className="messageText
colorDark">{ReactEmoji.emojify(text)}</p>
</div>
<p className="sentText pl-10">{user}</p>
</div>
)
)

export default Message;

9) TextContainer.js:
import React from 'react';
import { bubble as Menu } from 'react-burger-menu';
import onlineIcon from '../../icons/onlineIcon.png';

import './TextContainer.css';

const TextContainer = ({ users }) => (


<div className="textContainer">
<Menu>
{
users
?(
<div>
<h1>People currently chatting:</h1>
<div className="activeContainer">
<h2>
{users.map(({name}) => (
<div key={name} className="activeItem menu-item">
<img alt="Online Icon" src={onlineIcon}/> { name}
</div>
))}
</h2>
</div>
</div>
)
: null
}
</Menu>
</div>
);

export default TextContainer;

10) index.js (server side):


const express = require("express");
const socketio = require("socket.io");
const cors = require("cors");
const http = require("http");

const { addUser, removeUser, getUser, getUsersInRoom } =


require("./users.js");
const PORT = process.env.PORT || 5000;
const router = require("./router");
corsOptions = {
cors: true,
origins: ["http://localhost:3000"],
};

const app = express();


const server = http.createServer(app);
const io = socketio(server, corsOptions);
app.use(router);
app.use(cors());
io.on("connection", (socket) => {
console.log("we have a new connection!!!!!!");

socket.on("join", ({ name, room }, callback) => {


const { error, user } = addUser({ id: socket.id, name, room });

if (error) return callback(error);

socket.emit("message", {
user: "admin",
text: `${user.name}, welcome to the room ${user.room}`,
});
socket.broadcast
.to(user.room)
.emit("message", { user: "admin", text: `${user.name}, has joined` });

socket.join(user.room);

io.to(user.room).emit("roomData", {
room: user.room,
users: getUsersInRoom(user.room),
});

callback();
});

socket.on("sendMessage", (message, callback) => {


const user = getUser(socket.id);

io.to(user.room).emit("message", { user: user.name, text: message });

callback();
});

socket.on("disconnect", () => {
const user = removeUser(socket.id);

if (user) {
io.to(user.room).emit("message", {
user: "admin",
text: `${user.name} has left.`,
});
io.to(user.room).emit("roomData", {
room: user.room,
users: getUsersInRoom(user.room),
});
}
});
});

server.listen(PORT, () => console.log(`Server has started on port $


{PORT}`));

11) router.js:
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {


res.send('server is up and running');
});

module.exports = router;

12) users.js:
const users = [];
const addUser = ({ id, name, room }) => {
name = name.trim().toLowerCase();
room = room.trim().toLowerCase();

const existingUser = users.find(


(user) => user.room === room && user.name === name
);

if (existingUser) {
return { error: "Username is taken, please take another one!" };
}

const user = { id, name, room };

users.push(user);
return { user };
};

const removeUser = (id) => {


const index = users.findIndex((user) => user.id === id);

if (index !== -1) {


return users.splice(index, 1)[0];
}
};
const getUser = (id) => users.find((user) => user.id === id);

const getUsersInRoom = (room) => users.filter((user) => user.room ===


room);

module.exports = { addUser, removeUser, getUser, getUsersInRoom };

13) style.css:
#page-wrap {
padding-bottom: 10px;
padding-top: 10px;
}
.outerContainer {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.4)),
url(../../icons/background2.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height: 100vh;
align-items: center;
}

.container {
display: flex;
flex-direction: column;
justify-content: space-between;
background: linear-gradient(
rgba(255, 255, 255, 0),
rgba(255, 255, 255, 0.2),
rgba(255, 255, 255, 0)
);
border-radius: 8px;
height: 95%;
}

@media (min-width: 320px) and (max-width: 600px) {


.outerContainer {
height: 100vh;
}

.container {
width: 95%;
height: 95vh;
background-size: 95vw 95vh;
}
}
@media (min-width: 600px) and (max-width: 1200px) {
.container {
width: 60%;
}
}
.infoBar {
display: flex;
align-items: center;
justify-content: space-between;
height: 60px;
width: 100%;
position: fixed;
}

.leftInnerContainer {
flex: 0.5;
display: flex;
align-items: center;
margin-left: 40%;
color: white;
}

.rightInnerContainer {
display: flex;
flex: 0.5;
justify-content: flex-end;
margin-right: 5%;
}

.onlineIcon {
margin-right: 5%;
}
.form {
display: flex;
}

.input {
border: 2px solid #05d0eb;
width: 80%;
border-right: none;
background: #e5e4e2;

font-size: 1.2em;
height: 50px;
padding-left: 5%;
border-top-left-radius: 50px;
border-bottom-left-radius: 50px;
}

input:focus,
textarea:focus,
select:focus {
outline: none;
}

.sendButton {
color: #fff !important;
text-transform: uppercase;
text-decoration: none;
background: #ff3131;
border: 2px solid #d2042d;
border-left: none;
height: 50px;
display: inline-block;
width: 20%;
cursor: pointer;
outline: none;
border-top-right-radius: 50px;
border-bottom-right-radius: 50px;
}
html,
body {
padding: 0;
margin: 0;
font-family: sans-serif;
background: #34495e;
}
#root {
height: 100vh;
}

*{
box-sizing: border-box;
}

.joinOuterContainer {
display: flex;
justify-content: center;
text-align: center;
background: url(../../icons/background.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height: 100vh;
align-items: center;
}

.joinInnerContainer {
width: 96%;
max-width: 350px;
background: none;
text-align: center;
border-radius: 10px;
padding-bottom: 40px;
}

.joinInput {
background: none;
display: block;
margin: 5px auto;
text-align: center;
border: 2px solid #05d0eb;
padding: 14px 10px;
width: 80%;
outline: none;
color: white;
border-radius: 30px;
transition: 0.25s;
}
.joinInput:focus {
width: 85%;
border-color: #2ecc71;
}

.heading {
color: white;
font-size: 2.5em;
padding-bottom: 10px;
border-bottom: 2px solid white;
text-shadow: 0 0 20px #fff, 0 0 10px #fff, 0 0 21px #fff, 0 0 42px #fff,
0 0 82px #fff, 0 0 92px #fff, 0 0 102px #fff, 0 0 151px #fff;
}

.button {
border: 0;
background: none;
display: block;
margin: 60px auto;
text-align: center;
border: 2px solid #2ecc71;
padding: 14px 40px;
outline: none;
color: white;
border-radius: 24px;
transition: 0.25s;
cursor: pointer;
}
.button:hover {
background: #2ecc71;
}

.mt-20 {
margin-top: 20px;
}
.messageBox {
background: #f3f3f3;
border-radius: 20px;
padding: 0px 10px;
color: white;
display: inline-block;
max-width: 80%;
}

.messageText {
width: 100%;
letter-spacing: 0;
float: left;
font-size: 1.1em;
word-wrap: break-word;
}

.messageText img {
vertical-align: middle;
}

.messageContainer {
display: flex;
justify-content: flex-end;
padding: 0 5%;
margin-top: 3px;
}

.sentText {
display: flex;
align-items: center;
font-family: Helvetica;
color: #fff;
letter-spacing: 0.3px;
}

.pl-10 {
padding-left: 10px;
}

.pr-10 {
padding-right: 10px;
}

.justifyStart {
justify-content: flex-start;
}

.justifyEnd {
justify-content: flex-end;
}
.colorWhite {
color: white;
}

.colorDark {
color: #353535;
}

.backgroundBlue {
background: #ff4500;
}

.backgroundLight {
background: #f3f3f3;
}
.messages {
padding: 5% 0;
overflow: auto;
flex: auto;
}
*{
box-sizing: border-box;
}

#page-wrap {
padding-bottom: 10px;
padding-top: 10px;
}
.textContainer {
display: flex;
flex-direction: column;
color: white;
height: 60%;
justify-content: space-between;
outline: none;
}

.activeContainer {
display: flex;
align-items: center;
}

.activeItem {
display: flex;
align-items: center;
}

.activeContainer img {
padding-right: 10px;
}
.textContainer h1 {
margin-bottom: 30px;
}
.bm-burger-button {
position: fixed;
width: 20px;
height: 15px;
left: 36px;
top: 36px;
}

/* Color/shape of burger icon bars */


.bm-burger-bars {
background: #fff;
}

/* Color/shape of burger icon bars on hover*/


.bm-burger-bars-hover {
background: #b8b7ad;
}

/* Position and sizing of clickable cross button */


.bm-cross-button {
height: 24px;
width: 24px;
}
/* Color/shape of close button cross */
.bm-cross {
background: #bdc3c7;
}

/*
Sidebar wrapper styles
Note: Beware of modifying this element as it can break the animations -
you should not need to touch it in most cases
*/
.bm-menu-wrap {
position: fixed;
height: 100%;
}

/* General sidebar styles */


.bm-menu {
background: #ff3131;
padding: 2.5em 1.5em 0;
font-size: 1.15em;
}

/* Morph shape necessary with bubble or elastic */


.bm-morph-shape {
fill: #ff3131;
}

/* Wrapper for item list */


.bm-item-list {
color: #fff;
padding: 0.8em;
}

/* Styling of overlay */
.bm-overlay {
background: rgba(0, 0, 0, 0.3);
}
.bm-item {
display: inline-block;

color: #fff;
margin-bottom: 10px;
text-align: left;
text-decoration: none;
transition: color 0.2s;
}

.bm-item:hover {
color: #ffffff;
}
Conclusion

This project is designed to meet the requirements of an online


chatting application. It serves as the platform for individuals to
come forward and use it to communicate with their friends and
family and their loved ones. It has an easy to use user interface and
its working is also not complex, we just have to login in a room with
our name and room id and we can invite our friends on the same
room to chat with you effortlessly. We can create unlimited number
of rooms in this application and we can also invite any number of
users in one room. It has been developed in ReactJs and Nodejs,
by keeping in mind the specification of the system.

For designing we have used simple data flow diagram.

Overall the project teaches us the essential skills like:

 Designing the front end with React


 Developing back end or server with node js and server.
 Real time communication with web sockets and socket IO.
Bibliography

1) JavaScript Mastery Youtube page.

2) Css-tricks.com.

3) Github.com.

4) Stack Overflow.

5) Socket IO Documentation.

You might also like