a. 安装

	pip3 install gevent-websocket 

	作用:
- 处理Http、Websocket协议的请求 -> socket
- 封装Http、Websocket相关数据 -> request

b. 基本结构

	from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer @app.route('/test')
def test():
ws = request.environ.get('wsgi.websocket')
ws.receive()
ws.send(message)
ws.close()
return render_template('index.html') if __name__ == '__main__':
http_server = WSGIServer(('0.0.0.0', 5000,), app, handler_class=WebSocketHandler)
http_server.serve_forever()

c. WEB聊天室:

	后端:
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from flask import Flask,render_template,request
import pickle app = Flask(__name__)
app.secret_key = 'xfsdfqw' @app.route('/index')
def index():
return render_template('index.html') WS_LIST = [] @app.route('/test')
def test():
ws = request.environ.get('wsgi.websocket')
if not ws:
return '请使用WebSocket协议'
# websocket连接已经成功
WS_LIST.append(ws)
while True:
# 等待用户发送消息,并接受
message = ws.receive() # 关闭:message=None
if not message:
WS_LIST.remove(ws)
break for item in WS_LIST:
item.send(message) return "..." if __name__ == '__main__':
http_server = WSGIServer(('0.0.0.0', 5000,), app, handler_class=WebSocketHandler)
http_server.serve_forever() 前端:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<style>
.msg-item{
padding: 5px;
border: 1px;
margin: 0 5px;
}
</style>
</head>
<body>
<h1>首页</h1>
<div>
<h2>发送消息</h2>
<input id="msg" type="text" /> <input type="button" value="发送" onclick="sendMsg()">
<h2>接收消息</h2>
<div id="container"> </div>
</div> <script src="/static/jquery-3.3.1.min.js"></script>
<script> ws = new WebSocket('ws://192.168.12.42:5000/test');
ws.onmessage = function (event) {
var tag = document.createElement('div');
tag.className = 'msg-item';
tag.innerText = event.data;
$('#container').append(tag);
} function sendMsg() {
ws.send($('#msg').val());
} </script>
</body>
</html>

d. tornado.websocket示例

			import tornado
from tornado.web import Application
from tornado.web import RequestHandler
from tornado.websocket import WebSocketHandler class IndexHandler(RequestHandler): def get(self, *args, **kwargs):
# self.write('Hello World')
self.render('index.html') def post(self, *args, **kwargs):
user = self.get_argument('user')
self.write('成功') WS_LIST = []
class MessageHandler(WebSocketHandler): def open(self, *args, **kwargs):
WS_LIST.append(self) def on_message(self, message):
for ws in WS_LIST:
ws.write_message(message) def on_close(self):
WS_LIST.remove(self) settings = {
'template_path':'templates',
'static_path':'static',
} app = Application([
(r"/index", IndexHandler),
(r"/message", MessageHandler),
],**settings) if __name__ == '__main__':
app.listen(address='0.0.0.0',port=9999)
tornado.ioloop.IOLoop.instance().start()

WebSocket 在烧瓶和龙卷风中的应用的更多相关文章

  1. Tornado.web.Application之-settings

    应用程序配置 class  tornado.web.Application(handlers:List [Union [Rule,Tuple]] = None,default_host:str = N ...

  2. 漫扯:从polling到Websocket

    Http被设计成了一个单向的通信的协议,即客户端发起一个request,然后服务器回应一个response.这让服务器很为恼火:我特么才是老大,我居然不能给小弟发消息... 轮询 老大发火了,小弟们自 ...

  3. 细说WebSocket - Node篇

    在上一篇提高到了 web 通信的各种方式,包括 轮询.长连接 以及各种 HTML5 中提到的手段.本文将详细描述 WebSocket协议 在 web通讯 中的实现. 一.WebSocket 协议 1. ...

  4. java使用websocket,并且获取HttpSession,源码分析

    转载请在页首注明作者与出处 http://www.cnblogs.com/zhuxiaojie/p/6238826.html 一:本文使用范围 此文不仅仅局限于spring boot,普通的sprin ...

  5. WebSocket - ( 一.概述 )

    说到 WebSocket,不得不提 HTML5,作为近年来Web技术领域最大的改进与变化,包含CSS3.离线与存储.多媒体.连接性( Connectivity )等一系列领域,而即将介绍的 WebSo ...

  6. php+websocket搭建简易聊天室实践

    1.前言 公司游戏里面有个简单的聊天室,了解了之后才知道是node+websocket做的,想想php也来做个简单的聊天室.于是搜集各种资料看文档.找实例自己也写了个简单的聊天室. http连接分为短 ...

  7. Demo源码放送:打通B/S与C/S !让HTML5 WebSocket与.NET Socket公用同一个服务端!

    随着HTML5 WebSocket技术的日益成熟与普及,我们可以借助WebSocket来更加方便地打通BS与CS -- 因为B/S中的WebSocket可以直接连接到C/S的服务端,并进行双向通信.如 ...

  8. Cowboy 开源 WebSocket 网络库

    Cowboy.WebSockets 是一个托管在 GitHub 上的基于 .NET/C# 实现的开源 WebSocket 网络库,其完整的实现了 RFC 6455 (The WebSocket Pro ...

  9. 借助Nodejs探究WebSocket

    文章导读: 一.概述-what's WebSocket? 二.运行在浏览器中的WebSocket客户端+使用ws模块搭建的简单服务器 三.Node中的WebSocket 四.socket.io 五.扩 ...

随机推荐

  1. Linux常用命令(更新)

  2. 常用模块(hashlib,configparser,logging)

    常用模块(hashlib,configparser,logging) hashlib hashlib 摘要算法的模块md5 sha1 sha256 sha512摘要的过程 不可逆能做的事:文件的一致性 ...

  3. MAC下配置MAVEN环境变量配置

    MAVEN环境变量的配置: 第一步:在MAVEN的官网下载MAVEN.http://maven.apache.org/download.cgi,我这里下载的是apache-maven-3.39-bin ...

  4. pytharm提示过期 License Activation 解决办法

    遇到如下问题: 打开网站:  http://idea.lanyus.com/   next next ok    

  5. netty应用

    http://www.blogjava.net/yongboy/archive/2013/05/13/399203.html http://shentar.me/tag/netty-2/ 代理 htt ...

  6. svn / git SourceTree

    开发使用SourceTree 忽略文件这块老弄错,这次专门博客一下,使用CocoaPods 开发项目, 忽略步骤如下:  忽略文件内容如下 *.xcworkspace xcuserdata *.loc ...

  7. grid布局笔记

    1.应用 display: grid 的元素.这是所有网格项(Grid Items)的直接父级元素.即容器 2.网格容器(Grid Container)的子元素(直接子元素). 3.注意:在 网格容器 ...

  8. React-native Android环境搭建

    基础安装 安装Homebrew Homebrew是Mac OSX的包管理器,我们需要通过Homebrew安装开发React Native的相关软件包. 如果不知道怎样安装Homebrew可以点这里:官 ...

  9. 存在单点故障的namenode宕机恢复测试

    前提:如果namenode没有做HA,那么至少应该启用secondarynamenode,以便namenode宕机之后手动恢复数据 实验环境:3个节点(cenos 6.10) 测试前数据: 1.为了确 ...

  10. jar包错误

    Exception in thread "main" java.lang.NoSuchMethodError: org.slf4j.spi.LocationAwareLogger. ...