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. [intellij]create gradle project

    https://intellij-support.jetbrains.com/hc/en-us/community/posts/206806425/comments/206797339

  2. 236. Lowest Common Ancestor of a Binary Tree(最低公共祖先,难理解)

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...

  3. 437. Path Sum III(路径可以任意点开始,任意点结束)

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  4. Linux下SSH中配置说明

    SSH 协议:安全外壳协议.为 Secure Shell 的缩写.SSH 为建立在应用层和传输层基础上的安全协议. sshd服务使用SSH协议可以用来进行远程控制,或在计算机之间传送文件.而实现此功能 ...

  5. JavaScript与Java数据类型的区别

    今天开始正式认真学习js,虽然在平常j2ee开发中也经常用到JS但并不精通,这次随笔记下js与Java数据类型的不同之处 Number 与java不同,js作为弱类型语言即使在浮点数与整数上也未作明确 ...

  6. cordova 5.0版本说明

    2015/04/21发布Cordova 5.0.0! 1)插件从Cordova plugins registry(CPR)全部移到npm,并且重新命名 ***org.apache.cordova.* ...

  7. 14.python模块之subprocess

    我们几乎可以在任何操作系统上通过命令行指令与操作系统进行交互,比如Linux平台下的shell.那么我们如何通过Python来完成这些命令行指令的执行呢?另外,我们应该知道的是命令行指令的执行通常有两 ...

  8. COS-6主存管理

    操作系统是用户和计算机的接口,同时也是计算机硬件和其他软件的接口.操作系统的功能包括管理计算机系统的硬件.软件及数据资源,控制程序运行,改善人机界面,为其它应用软件提供支持,让计算机系统所有资源最大限 ...

  9. Python中求阶乘(factorial)

    1. math.factorial(x) import math value = math.factorial(x) 2. reduce函数 def factorial(n): return redu ...

  10. MVC viewbag & viewdata

    弱类型:ViewData[""] 动态型:ViewBag dynamic ViewData 是字典型的(Dictionary),ViewBag 不再是字典的键值对结构,而是dyna ...