tornado websocket 客户端与服务器端示例
🕕 by pyList at 2014-11-09 17:08
最近在网上找了些websocket的资料看了下,node和tornado等等本身已经实现了websocket的封装,所以使用起来会比较简单,php如果想要写websocket还需要自己跑一整套流程,比较麻烦。
根据网上的资料写了一个简单的 websocket 的demo,果真炫酷掉渣天,我是用tornado
,网上多是实现实时聊天室的例子,想要实现点对点的聊天功能还需要在send函数那里加条件,目测是根据浏览器用户的id去判断的。代码如下:
服务端代码
#!/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()
客户端代码
<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>
本文网址: https://pylist.com/t/1415524109 (转载注明出处)
如果你有任何建议或疑问可以在下面 留言
发表第一条评论!
相关推荐
小工具
标签
websocket
tornado
客户端
搭建
聊天
服务
示例
sae
python
pytenjin
asynchronous
gen
long
poll
推送
跨域
server
问题
subprocess
阻塞
调用
tcpclient
4.0
简化
ffmpeg
一览表
参数
code
handshake
unexpected
400
bbr
openwrt
路由
开启
utf
gbk
big5
golang
转换
google
身份验证
authenticator
迁移
手机
linux
ulimit
永久
设置
系统
app
mac
store
登录
未知
国外
vps
nginx
反向
访问
国内
上传
服务器
中断
文件
usb
上网卡
共享
网络
form
data
post
硬件加速
ubnt
er
固件
go2o
开源
完整
商业
spotify
chartify
图表
乱码
vim
中文
解决
正则
字符串
切割
最新版
wndr4300
升级
自动更新
microsoft
关闭
静音
风扇
主机
笔记本
改造
低功耗
web
爬虫
组装
微信
尝鲜
视频
体验
cpu
debian
ubuntu
查看
温度
chrome
浏览
webdriver
微博
selenium
gnu
安装
系统启动
编译
宅家
坑记
屏幕
动手
quic
抢先
useragent
搜索引擎
蜘蛛
真假
识别
最近发表
- Mac 关闭 Microsoft 自动更新
- Mac 登录 App Store 出现“发生了未知错误”的解决方法
- 老笔记本改造为无风扇静音主机方案
- 自己组装21瓦低功耗家庭爬虫、文件、web服务器
- 微信视频号尝鲜体验
- Ubuntu/Debian 查看CPU温度的方法
- 在Ubuntu/debian Server 系统使用Chrome 无头浏览模式
- 换手机后 Google 身份验证器 Google Authenticator 数据迁移的简单方法
- 使用Golang selenium WebDriver 自动登录微博
- 在 Ubuntu 或其它 GNU/Linux 系统下安装 Debian
- Mac 下制作 USB ubuntu/debian 系统启动、安装盘的几种方法
- ubuntu/debian 下自行编译 OpenWRT 固件
- 宅家自己动手换手机屏幕掉坑记
- 路由 UBNT ER-X 官方固件升级及开启硬件加速的方法
- 在 Nginx 和 Golang web 上抢先体验 QUIC
- 从UserAgent识别搜索引擎并判断真假蜘蛛
最近浏览
- Openwrt 路由上开启BBR
- Golang 实现 GBK、Big5、UTF-8 之间的转换
- 换手机后 Google 身份验证器 Google Authenticator 数据迁移的简单方法
- Linux 系统永久设置ulimit
- Mac 登录 App Store 出现“发生了未知错误”的解决方法
- 在国外vps 上配置nginx 作反向代理访问国外网站
- OpenWrt 国内源
- Nginx 服务器上传大文件经常中断的解决方法
- Openwrt 使用USB 4G 上网卡共享网络
- python form-data post上传数据简便方法
- 路由 UBNT ER-X 官方固件升级及开启硬件加速的方法
- go2o: 一个完整的golang 商业开源项目
- Spotify开源的Python图表生成库chartify
- linux vim 中文显示乱码的解决方法
- Golang 正则切割字符串
- WNDR4300 固件升级到 OpenWrt 最新版