Skip to content

Instantly share code, notes, and snippets.

@gdemir
Created April 10, 2015 08:53
Show Gist options
  • Save gdemir/dc26499af4a3ba7d86e3 to your computer and use it in GitHub Desktop.
Save gdemir/dc26499af4a3ba7d86e3 to your computer and use it in GitHub Desktop.
Tornado ile Websocket Mini Chat Programı
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div style="height:400px;">
<div style="float:left;width:150px;">
<ul class="users">
</ul>
</div>
<div style="float:left;margin-left:40px;width:400px;">
<ul class="messages">
</ul>
</div>
</div>
<form action="" id="form-message">
<input type="text" id="input-message-body">
</form>
<button class="btn-logout">Çıkış</button>
<script type="text/javascript">
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
var username = guid();
//console.log(username);
var ws = new WebSocket("ws://localhost:8888/websocket?id=" + username );
ws.onopen = function() {
// ws.send(JSON.stringify(j));
};
ws.onmessage = function (evt) {
// console.log(evt);
// main.py dosyasındaki on_message() fonskiyonunda write_messages() fonksiyonun yolladığı veriyi json'dan dict'e çevir: DICT
var receivedData = $.parseJSON(evt.data);
if (receivedData.type=="new_message") {
var html = "<li><span style='color:red;'>" + receivedData.user_id + "</span> : " + receivedData.message_body + "</li>";
$(".messages").append(html)
}else if(receivedData.type=="new_user"){
var html = "<li id='"+receivedData.user_id+"'><span style='color:blue;'>" + receivedData.user_id + "</span></li>";
$(".users").append(html)
}else if(receivedData.type=="user_list"){
$.each(receivedData.users_ids, function(index, userId) {
var html = "<li id='"+receivedData.user_id+"'><span style='color:blue;'>" + userId + "</span></li>";
$(".users").append(html)
});
}else if(receivedData.type=="user_logout"){
$(".users").find("#" + receivedData.user_id).fadeOut("slow")
}
};
ws.onclose = function() {
};
$(function() {
$("#form-message").on("submit", function () {
var messageBody = $("#input-message-body").val();
var sendMessage = { "message_body" : messageBody }
// console.log(JSON.stringify(sendMessage));
// console.log(messageBody);
ws.send(JSON.stringify(sendMessage));
$("#input-message-body").val("");
return false;
});
$(".btn-logout").on("click",function () {
ws.close();
})
});
</script>
</body>
</html>
# -*- coding: utf-8 -*-
import tornado.ioloop
import tornado.web
import tornado.websocket
import json
from tornado.options import define, options, parse_command_line
define("port", default=8888, help="run on the given port", type=int)
# we gonna store clients in dictionary..
clients = dict()
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self, *args):
self.id = self.get_argument("id")
clients[self.id] = { "id" : self.id, "self" : self }
# yeni baglanti yapan cliente önceki user verilerini usersIds dictine yükle
usersIds = []
for key, client in clients.iteritems():
usersIds.append(client["id"])
# yeni baglanti yapan cliente önceki user verilerini yolla dicten jsona cevir -> JSON
sendMessage = json.dumps({ "type" : "user_list" , "users_ids" : usersIds })
self.write_message(sendMessage)
# yeni baglanan clienti tüm bagli clientlere göstermek icin dict'ten jsona cevir -> JSON
sendMessage = json.dumps({ "type" : "new_user" , "user_id" : self.id })
# yeni baglanan clienti kendisi haric bagli olan clientlere göstermek yolla
for key, client in clients.iteritems():
if client["id"] != self.id:
client["self"].write_message(sendMessage)
def on_message(self, receivedData):
# index.html'deki .send() fonksiyonundan gelen mesaji json mesaji dicte cevir -> DICT
jsonData = json.loads(receivedData);
# kendi user_id'sini ve mesaj metni göndermek icin dict'ten jsona cevir -> JSON
sendMessage = json.dumps({ "type" : "new_message", "message_body" : jsonData["message_body"], "user_id" : str(self.id) })
# tüm istemcilere bu mesajı yolla #TODO sadece bazılarına basılacak
for key, client in clients.iteritems():
client["self"].write_message(sendMessage)
def on_close(self):
if self.id in clients:
del clients[self.id]
sendMessage = json.dumps({ "type" : "user_logout", "user_id" : str(self.id) })
for key, client in clients.iteritems():
client["self"].write_message(sendMessage)
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
#self.write("This is your response")
self.render("index.html")
#we don't need self.finish() because self.render() is fallowed by self.finish() inside tornado
#self.finish()
app = tornado.web.Application([
(r'/', IndexHandler),
(r'/websocket', WebSocketHandler),
])
if __name__ == '__main__':
parse_command_line()
app.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment