1. Install node.js environment and modules
2. Create a template application using express module
3. Install Eclipse IDE and node.js plugin
Now let's start building our chat application. PLEASE work with Google Chrome. I didn't test it on other browsers and i'm not sure about it's compitability.
First of all, I've searched for a decent CSS for chat, so I googled and found that post:
Create "stylesheets" under "public" directory and add "chat.css".
We are ready to write some code!
Creating the chat view
1. Create "chat.hjs" under "views" folder. ".hjs" extension tells the engine it's a hogan.js template.
2. At first, we'll include socket.io.js file and jquery (although I'm not sure we will be using the last).
<html>
<head>
<link rel='stylesheet' href='/stylesheets/chat.css' />
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</body>
</html>
3. Creating the view includes:
"upperPanel" - divided to two list: "chat" for the chat messages, "friends" for the chat users list.
"bottomPanel" - divided to two panels:
"messagePanel" - contains text area for the user to send messages, and a "send" button. Please note the onclick="onSendMessageClick()".
"signInPanel" - contains text box for the user to enter his chat user-name, and a "LogIn" button. Please note the onclick="onLogInLogOutClick()".
<div id="wrapper">
<div id="upperPanel">
<div>
<ul id="chat">
</ul>
</div>
<div>
<ul id="friends">
</ul>
</div>
</div>
<div id="bottomPanel">
<div id="messagePanel" style="float:left">
<textarea id="txtUserMessage" style="resize:none;height:80px;float:left;width:800px;"></textarea>
<input id="btnSendMessage" onclick="onSendMessageClick()" type="submit" style="width:50px;height:80px;float:right;" disabled="disabled" value="send" />
</div>
<div id="signInPanel" style="float:right">
<input id="txtUserName" style="width:130px;" type="text" name="userName"/>
<button id="btnLogInLogOut" onclick="onLogInLogOutClick()">LogIn</button>
</div>
</div>
</div>
Also add session id div, just in order to demonstrate hogan.js:
<div id="sessionId" style="float:right">
Session Id: {{sessionId}}
</div>
The curly buckets mention that this data would be injected from the server.
Server
4. Server configurations and events
Let's take a break from the client-side, and move to write some node.js server code. We had just written a server call, so let's try to catch it.
A.
Open app.js, which is the main file of our server application. This is where all starts.
Please remove all code before you continue.
B.
Add those module imports including socket.io on top:
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, socketio = require('socket.io') // library for realtime web applications based on WebSocket protocol
C.
Create the server, and make socket.io availiable on server by:
var app = express()
, server = http.createServer(app)
, io = socketio.listen(server);
D.
Add those configurations to your express application:
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'hjs');
app.use(express.favicon());
//app.use(express.logger('dev')); // Express logger
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser()); // To parse cookies
app.use(express.session({secret: '1234567D9sQWERTY'})); // To use sessions
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
You can see that we are setting the port of our server application, defining what is our view engine (hogan.js) and so on. We are doing this with app.set().
The app.use() calls pass 'middleware' functions for express to use. Each layer is essentially adding a function that specifically handles something to the flow through the middleware.
For example by adding "app.use(express.bodyParser());", we ensure that our server handles incoming requests through the express middleware, and now parsing the body of incoming requests is part of the procedure that the app middleware takes when handling incoming requests.
Also add:
app.configure('development', function(){
app.use(express.errorHandler());
});
That line would tell our app to use the middleware errorHandler function when running on development mode. (We can run development mode by writing: process.env.NODE_ENV='development' in our node app)
E.
Start the server on the chosen port by adding:
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
F.
Now we want to configure routing for our app.
We want our chat app to be placed at: "{URL}/chat".
Add to app.js:
require('./routes')(app);
And modify index.js to:
module.exports = function(app) {
app.get('/', index);
app.get('/chat',chat);
};
var index = function(req, res){
res.render('index', { title: 'Express' });
};
var chat = function(req, res){
res.render('chat', { sessionId: req.session.id});
};
"app.get('/chat',chat);" - sends all GET requests of '/chat' to 'chat' function we have defined.
"res.render('chat', { sessionId: req.session.id});" - that line tells the engine to render 'chat.hjs' view, and to inject the user's session id.
Summary
In that part we created a basic chat view, and set some configurations to our server.
Now we are all set to create the communication between the clients and server.
The curly buckets mention that this data would be injected from the server.
Server
4. Server configurations and events
A.
Open app.js, which is the main file of our server application. This is where all starts.
Please remove all code before you continue.
B.
Add those module imports including socket.io on top:
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, socketio = require('socket.io') // library for realtime web applications based on WebSocket protocol
C.
Create the server, and make socket.io availiable on server by:
var app = express()
, server = http.createServer(app)
, io = socketio.listen(server);
D.
Add those configurations to your express application:
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'hjs');
app.use(express.favicon());
//app.use(express.logger('dev')); // Express logger
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser()); // To parse cookies
app.use(express.session({secret: '1234567D9sQWERTY'})); // To use sessions
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
You can see that we are setting the port of our server application, defining what is our view engine (hogan.js) and so on. We are doing this with app.set().
The app.use() calls pass 'middleware' functions for express to use. Each layer is essentially adding a function that specifically handles something to the flow through the middleware.
For example by adding "app.use(express.bodyParser());", we ensure that our server handles incoming requests through the express middleware, and now parsing the body of incoming requests is part of the procedure that the app middleware takes when handling incoming requests.
Also add:
app.configure('development', function(){
app.use(express.errorHandler());
});
That line would tell our app to use the middleware errorHandler function when running on development mode. (We can run development mode by writing: process.env.NODE_ENV='development' in our node app)
E.
Start the server on the chosen port by adding:
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
F.
Now we want to configure routing for our app.
We want our chat app to be placed at: "{URL}/chat".
Add to app.js:
require('./routes')(app);
And modify index.js to:
module.exports = function(app) {
app.get('/', index);
app.get('/chat',chat);
};
var index = function(req, res){
res.render('index', { title: 'Express' });
};
var chat = function(req, res){
res.render('chat', { sessionId: req.session.id});
};
"app.get('/chat',chat);" - sends all GET requests of '/chat' to 'chat' function we have defined.
"res.render('chat', { sessionId: req.session.id});" - that line tells the engine to render 'chat.hjs' view, and to inject the user's session id.
Summary
In that part we created a basic chat view, and set some configurations to our server.
Now we are all set to create the communication between the clients and server.
I found this post very interesting and valuable. keep posting it is really helpful.
ReplyDeleteNode JS Online training
Node JS training in Hyderabad
instagram takipçi satın al
ReplyDeleteucuz takipçi
takipçi satın al
https://takipcikenti.com
https://ucsatinal.org
instagram takipçi satın al
https://perdemodelleri.org
https://yazanadam.com
instagram takipçi satın al
balon perdeler
petek üstü perde
mutfak tül modelleri
kısa perde modelleri
fon perde modelleri
tül perde modelleri
https://atakanmedya.com
https://fatihmedya.com
https://smmpaketleri.com
https://takipcialdim.com
https://yazanadam.com
yasaklı sitelere giriş
aşk kitapları
yabancı şarkılar
sigorta sorgula
https://cozumlec.com
word indir ücretsiz
tiktok jeton hilesi
rastgele görüntülü sohbet
fitness moves
gym workouts
https://marsbahiscasino.org
http://4mcafee.com
http://paydayloansonlineare.com
perde modelleri
ReplyDeletenumara onay
mobil ödeme bozdurma
Nftnasilalinir
ANKARA EVDEN EVE NAKLİYAT
trafik sigortasi
Dedektör
HTTPS://KURMA.WEBSİTE/
Ask Romanlari
Smm Panel
ReplyDeleteSmm Panel
iş ilanları
instagram takipçi satın al
hirdavatciburada.com
beyazesyateknikservisi.com.tr
SERVİS
Tiktok Hile İndir
ataşehir beko klima servisi
ReplyDeletekadıköy lg klima servisi
maltepe alarko carrier klima servisi
kadıköy alarko carrier klima servisi
maltepe daikin klima servisi
kartal toshiba klima servisi
ümraniye toshiba klima servisi
kartal beko klima servisi
beykoz lg klima servisi
özel ambulans
ReplyDeletenft nasıl alınır
en son çıkan perde modelleri
yurtdışı kargo
lisans satın al
uc satın al
en son çıkan perde modelleri
minecraft premium
Good content. You write beautiful things.
ReplyDeletevbet
mrbahis
sportsbet
korsan taksi
vbet
hacklink
mrbahis
hacklink
sportsbet
dijital kartvizit
ReplyDeletereferans kimliği nedir
binance referans kodu
referans kimliği nedir
bitcoin nasıl alınır
resimli magnet
XTR
hatay
ReplyDeletekars
mardin
samsun
urfa
FS45CR
https://istanbulolala.biz/
ReplyDeleteXNS
kayseri evden eve nakliyat
ReplyDeleteaydın evden eve nakliyat
kütahya evden eve nakliyat
gümüşhane evden eve nakliyat
balıkesir evden eve nakliyat
4GE
hatay evden eve nakliyat
ReplyDeleteısparta evden eve nakliyat
erzincan evden eve nakliyat
muğla evden eve nakliyat
karaman evden eve nakliyat
8OYS
düzce evden eve nakliyat
ReplyDeletedenizli evden eve nakliyat
kırşehir evden eve nakliyat
çorum evden eve nakliyat
afyon evden eve nakliyat
ULE2U
CC5DE
ReplyDeleteAltındağ Parke Ustası
Muş Şehirler Arası Nakliyat
Eryaman Boya Ustası
Ünye Oto Lastik
Keçiören Boya Ustası
Maraş Evden Eve Nakliyat
Sivas Şehir İçi Nakliyat
Sincan Parke Ustası
Afyon Şehir İçi Nakliyat
AEABA
ReplyDeleteKayseri Parça Eşya Taşıma
Kırklareli Evden Eve Nakliyat
Rize Parça Eşya Taşıma
Karaman Şehirler Arası Nakliyat
Etimesgut Boya Ustası
Antalya Lojistik
Bitci Güvenilir mi
Burdur Evden Eve Nakliyat
Sinop Şehir İçi Nakliyat
74A6E
ReplyDeleteBinance Yaş Sınırı
Coin Madenciliği Siteleri
Coin Madenciliği Nasıl Yapılır
Bitcoin Nasıl Kazılır
Bitcoin Nasıl Kazanılır
Bulut Madenciliği Nedir
Kripto Para Nasıl Çıkarılır
Binance Borsası Güvenilir mi
Coin Nasıl Alınır
C73C6
ReplyDeleteKripto Para Kazanma
Coin Kazanma Siteleri
Kripto Para Madenciliği Nasıl Yapılır
Coin Nasıl Oynanır
Yeni Çıkacak Coin Nasıl Alınır
Binance Borsası Güvenilir mi
Binance Nasıl Kayıt Olunur
Bitcoin Oynama
Kripto Para Nasıl Çıkarılır
BDDC2
ReplyDeletereferans kimliği nedir
binance referans kodu
binance referans kodu
binance referans kodu
resimli magnet
resimli magnet
binance referans kodu
referans kimliği nedir
resimli magnet
D1738
ReplyDeleteamiclear
97348
ReplyDeletebitmex
aax
referans kodu
gate io
huobi
binance 100 dolar
bingx
kızlarla canlı sohbet
probit
B2E87
ReplyDeletebinance referans kod
coinex
bitcoin nasıl kazanılır
probit
bitcoin seans saatleri
telegram kripto kanalları
binance
gate io
papaya meyvesi
6964D
ReplyDeletekripto para nasıl alınır
bitget
binance referans
kaldıraç nasıl yapılır
referans kimligi nedir
probit
en az komisyon alan kripto borsası
canlı sohbet siteleri
bitget
تسليك مجاري aUuqGeqiqy
ReplyDeleteشركة عزل اسطح بالخرج Wsc8NE389T
ReplyDeleteشركة مكافحة الصراصير بالاحساء M19x1YwP8D
ReplyDeleteشركة مكافحة الصراصير بالاحساء opLogLI0z7
ReplyDeleteشركة عزل خزانات بخميس مشيط l1OMXp9489
ReplyDeleteشركة تنظيف افران
ReplyDeleteTvtkQ