Hi, this is a tutorial about how to build a chat app
here is it @Leroy01010
Let's start
1. Libraries
We need socket.io
to make a connection from user to a user.
And we need an express server, and also http.
Code:
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
2. Socket.io connection
We need some lines of code, to make a websocket connection.
The first block of code is for the username (for the chat app) and then to send: 'Username joined the chat...'
The second block of code is the opposite of the first one.
The third block of code is about the message, when the user sends a message, it will send his message with the username and the date of the message.
The fourth code block (outside of the websocket connection) is the port listen handler.
Code:
io.sockets.on('connection', (socket) => {
socket.on('username', function(username) {
socket.username = username;
io.emit('is_online', '🔵 <i>' + socket.username + ' joined the chat..</i>');
});
socket.on('disconnect', (username) => {
io.emit('is_online', '🔴 <i>' + socket.username + ' lefted the chat..</i>');
});
socket.on('chat_message', (message) => {
let time = new Date();
io.emit('chat_message',`<i>${time.toLocaleTimeString()}</i><br>` + '<strong>' + socket.username + '</strong>: ' + message);
});
});
// Server listen handler
server.listen(8080, ()=>{
console.log('Connected!');
});
4. Render the HTML file for the chat.
We need to add some lines before the socket connection.
To render the HTML chat app file.
Code:
app.get('/', function(req, res) {
res.sendFile(__dirname + "/index.html");
});
5. Fill the index.html with code to make a chat app.
We need to use jQuery to make a form for the chat.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Chatorzo</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #fff; padding: 3px; position: fixed; bottom: 0; width: 100%; border-color: #000; border-top-style: solid; border-top-width: 1px;}
form input { border-style: solid; border-width: 1px; padding: 10px; width: 85%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; margin-left: 2%; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
<script src="../../socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body style="background: grey;">
<header align="center">
<h1>Chatorzo</h1>
</header>
<br>
<br>
<br>
<ul id="messages"></ul>
<form action="/" method="POST" id="chatForm">
<input id="txt" autocomplete="off" autofocus="on" placeholder="Your message" /><button>Send</button>
</form>
<script>
var socket = io.connect('https://chatorzo-2.zdev1.repl.co');
$('form').submit(function(e){
e.preventDefault();
socket.emit('chat_message', $('#txt').val());
$('#txt').val('');
return false;
});
socket.on('chat_message', function(msg){
$('#messages').append($('<li>').html(msg));
});
socket.on('is_online', function(username) {
$('#messages').append($('<li>').html(username));
});
var username = prompt('Username:');
socket.emit('username', username);
</script>
</body>
</html>
So we basically added some CSS and some javascript (jQuery) to:
- Make it responsive and beautiful.
- Connect the socket code to the HTML file.
And that's it
Have a great day!
Source code: https://repl.it/@ZDev1/chatorzo-2
Well done zohdi
You are awesome
@moradz Thanks!
Kind of good and bad... good: it’s a wonderful chat app. Bad: it is connected through all repls? I followed all the steps above, and sent some messages, at the same time opened up another tab with your repl and yeah saw the messages i sent...
Is there any way to make it more private(like only people with my repl project link can see the messages)?
@nngggaming I have used Socket.IO
which it let's you to connect users to other users.
It is not a database, messages aren't saved in the database, only if someone joined the repl (if one of your family or friends or people on repl.it) can see messages on this web.
Hey @ZDev1 im AnonymousSquid10 on Github
ooooooooo very noice @ZDev1 ;)
@KobeFF thanks!!
This may be a stupid question but I'm rather new to coding and I'm unsure of where to place the code for rendering the HTMl
@M4urice it is fine
first, just make a HTML file (index.html)
And this block of code, renders the html file:
app.get('/', function(req, res) {
res.sendFile(__dirname + "/index.html");
});
And then you'll be ready :)
Thanks for the help @ZDev1
@M4urice gud np
It says .io isnt defined.
@ColeBosman weird
io is defined!
@ZDev1 Do you know any potential fixes?
@ColeBosman no cos it is working
@ZDev1 Let me try again.
=)
@ColeBosman ok sure
It's XSS-vulnerable.
@oignons no it's not
I feel...so lost.... :(
I can’t understand the html stuff very well without any explanations or breaking down.
@Highwayman oh sorry
I'll explain to you:
in the HTML file, we did:
- Styling to make it colorful (not a lot)
- And then I wrote then socket.io cdn for the chat, and a jQuery cdn
- And then this
<ul>
is the messages container
When someone sends a message it will append in it as a<li>
element - And the form is where you need to write your message
- And the script tag, I wrote in it some code to:
- connect the websocket to the website
- make a little bit jQuery code to submit the form when you send a message
- and some append things (I explained in this comment)
and then the username, it will be as a javascript prompt!
And that's it!
Wow thank you, very succinct! The ul thing is neat :)
@ZDev1
@Highwayman ye thanks :)
lefted the chat.
left* the chat
Also when trying to send message
Cannot POST /
@ZDev1 Cannot POST / when trying to send msg
@retronbv ok ok, I AM TRYING TO FIX THIS
@ZDev1 SHEESH OK IM JUST TRYING TO GIVE YOU ALL THE ERRORS I FOUND
@retronbv it is fixed now
Join chatorzo @ZDev1
@Highwayman lmao same
The best of times lol
@ZDev1
@Highwayman XD nice
ReferenceError: Server is not defined
any fix?
@ZenoxHosting can you screenshot it?
@ZenoxHosting done it is working now
@ZDev1 Okay thank you so much
@EpicGamer007 Ew light theme /s
@CodeLongAndPros , im on school comp, i cant download extensions :(
@EpicGamer007 Uh Repl ide has dark enabled?
@CodeLongAndPros , the ide has dark enabled yes
@EpicGamer007 fixed!
How is it related to repl? That’s the default ejs error page. It’s actually @ZDev1 who is responsible for the light theme @CodeLongAndPros
@agent9002 he means that he isn't using an extension that makes every website (error page is a website) has a dark theme
Kinda cringe ngl @ZDev1
@ZDev1 No, the Console is light theme, which sucks.
@CodeLongAndPros ¯_(ツ)_/¯
@ZDev1 (\\)btw?
@CodeLongAndPros yes md sucks
@ZDev1 , since when did md suck?
@EpicGamer007 md sucks when you're trying to do ascii
@ZDev1 , oh yea lol
Wow! This is really cool! More node tuts plez! I definetly wanna try this.
@EpicGamer007 ok thanks!
nice!!
@Leroy01010 thanks!
Learn it and submit your mission to your teacher!
That is a great chat app. But I have found a tool called Google Firebase that actually handles all the backend database for you. Check out the chatting app I made with Firebase: https://repl.it/talk/share/Chat-App-Using-Firebase-Realtime-Database/55382
If you want a tutorial on how to make this, then please upvote!
@Muhammad_SJC this is cool!
nice chat!
I know what is firebase, I'll learn it
but tell me, why did you make the username as a javascript prompt?
you can do a google auth with firebase!
@ZDev1 I know and I am working on it, but this is just a prototype
@Muhammad_SJC ok