tornado的websocket

本文介绍了一个简单的WebSocket聊天室应用的实现方法。客户端使用HTML和JavaScript建立WebSocket连接,并通过按钮发送消息。服务端采用Python和Tornado框架处理WebSocket连接,实现消息广播功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://haoningabc.iteye.com/blog/2154526
参考
http://www.tuicool.com/articles/niuqiiA
http://www.docin.com/p-278084273.html
http://www.tuicool.com/articles/QniyIz
客户端:
index.html


<html>
<head>
<script type="text/javascript">
var ws = new WebSocket("ws://182.254.155.153:8000/chat");
ws.onmessage = function(event) {
console.log(event);
}
ws.onopen = function() {
console.log('open');
};
ws.onclose = function() {
console.log('Closed! ');
}
function send() {
ws.send(document.getElementById('chat').value );
}
</script>
</head>

<body>
<div>
hello
<input id="chat">
<button onclick="send()">send</button>
</div>
</body>
</html>



服务端:


#!/usr/bin/python
#coding:utf-8
import os.path

import tornado.httpserver
import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpclient
import tornado.websocket

import json
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")

class SocketHandler(tornado.websocket.WebSocketHandler):
"""docstring for SocketHandler"""
clients = set()

@staticmethod
def send_to_all(message):
for c in SocketHandler.clients:
c.write_message(json.dumps(message))

def open(self):
self.write_message(json.dumps({
'type': 'sys',
'message': 'Welcome to WebSocket',
}))
SocketHandler.send_to_all({
'type': 'sys',
'message': str(id(self)) + ' has joined',
})
SocketHandler.clients.add(self)

def on_close(self):
SocketHandler.clients.remove(self)
SocketHandler.send_to_all({
'type': 'sys',
'message': str(id(self)) + ' has left',
})

def on_message(self, message):
SocketHandler.send_to_all({
'type': 'user',
'id': id(self),
'message': message,
})

##MAIN
if __name__ == '__main__':
app = tornado.web.Application(
handlers=[
(r"/", IndexHandler),
(r"/chat", SocketHandler)
],
debug = True,
# template_path = os.path.join(os.path.dirname(__file__), "templates"),
# static_path = os.path.join(os.path.dirname(__file__), "static")
)
app.listen(8000)
tornado.ioloop.IOLoop.instance().start()


apt-get install python-virtualenv
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值