tornado websocket
来源:互联网 发布:matlab编程stephen 编辑:程序博客网 时间:2024/04/29 23:52
最近在网上找了些websocket的资料看了下,node和tornado等等本身已经实现了websocket的封装,所以使用起来会比较简单,php如果想要写websocket还需要自己跑一整套流程,比较麻烦。
根据网上的资料写了一个简单的websocket的demo,果真炫酷掉渣天,我是用tornado,网上多是实现实时聊天室的例子,想要实现点对点的聊天功能还需要在send函数那里加条件,目测是根据浏览器用户的id去判断的。代码如下:
服务端代码:
#!/usr/bin/python#coding:utf-8import os.pathimport tornado.httpserverimport tornado.webimport tornado.ioloopimport tornado.optionsimport tornado.httpclientimport tornado.websocketimport jsonclass IndexHandler(tornado.web.RequestHandler):def get(self):self.render("index.html")class SocketHandler(tornado.websocket.WebSocketHandler):"""docstring for SocketHandler"""clients = set()@staticmethoddef 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, })##MAINif __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()
客户端代码:
<html><head><script type="text/javascript">var ws = new WebSocket("ws://localhost:8000/chat");ws.onmessage = function(event) {console.log(event);}function send() {ws.send(document.getElementById('chat').value );}</script></head><body><div>hello<input id="chat"><button onclick="send()">send</button></div></body></html>
0 0
- tornado websocket
- tornado websocket 学习历程
- 用tornado实现websocket
- tornado websocket简单教程
- Tornado框架10-WebSocket
- [tornado]websocket 最简单demo
- 一个tornado websocket 客户端例子
- Tornado实现聊天室功能(websocket)
- tornado websocket 学习demo:简单聊天室
- tornado websocket调用时出现403错误
- tornado实现基于websocket的好友一对一聊天功能
- tornado websocket编程 (2): 简单购物车改进
- tornado websocket编程(1) 初识websocket ——简单购物车实现
- tornado
- Tornado
- Tornado
- tornado
- Tornado
- Android 的权限设置大全
- 网站设为首页和加入收藏JavaScript代码
- 删除没有头结点的链表指点节点操作
- 田亮晒森碟与海豚亲吻照 父女开心超有爱
- Windows下用python备份MySQL数据库
- tornado websocket
- ASIHTTPRequest 详解
- sdadsa
- 典型的notification一例——“点击Notification,打开浏览器”
- 查看 MySQL 数据库中每个表占用的空间大小
- C#学习之接口
- Input Controls-Pickers
- [Unity3D] 关于触屏用Ray来Hit场景中GameObject的笔记
- 工厂模式