websocket 介绍

.用户A 给 用户B 发送一条消息
问 用户B 多久可以收到 用户A 的消息
电子邮件 - 可能是 一周期的时间 及时性很差
传达室大爷 - 消息托付 及时性很差
即时通讯 - 连接不断开的 .轮询 长轮询 长连接
.轮询 Http
- 每秒钟发起至少100次,请求收取消息
- 客户端有一定的处理能力
- 服务器有极快的处理速度
缺点:客户端服务器,浪费资源严重,带宽浪费 .长轮询 Http
先去连接服务器,不断开连接,保持一定时间,断开瞬间再次发起连接
- 浪费服务器资源严重
- 节省客户端资源
- 相对实时性消息 .长连接 基于Http发起握手
保持和服务器的长连接永不断开 除非有一端主动发起断开请求
- 发是发 收是收 互不影响
- 在客户端 和 服务器上 各有一个轮询
- 双端分担压力
- 消息及时性 缺点:占用连接资源,占用网络资源

轮询

服务器主动给客户端发送消息
Web - Socket
客户端 与 服务器 达成一个协议
websocket 客户端 与 websocket 服务器 达成一个websocket协议
介绍引自  https://segmentfault.com/a/1190000012709475

群聊

from flask import Flask, request, render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket #语法提示用 app = Flask(__name__) #实例化
user_socket_list = [] @app.route('/conn_ws') #http 协议,
def ws_app(): user_socket = request.environ.get('wsgi.websocket') #type:WebSocket
user_socket_list.append(user_socket)
print(len(user_socket_list),user_socket_list) while True: # user_socket 是一个内存地址
msg = user_socket.receive() # hang 住了
print(msg) for usocket in user_socket_list:
usocket.send(msg) # print(request.environ)
# print(request.environ.get('wsgi.websocket'))#
# --> <geventwebsocket.websocket.WebSocket object at 0x0379A9D0> ws对象 # return '555' # 遇到retur就断了
# 状态1 已经开启了
# 3 开启了,断开了 @app.route('/')
def index():
return render_template('my_ws.html') if __name__ == '__main__':
# app.run()
http_serv = WSGIServer(('0.0.0.0',9009),app,handler_class=WebSocketHandler) # 应用程序网关接口
http_serv.serve_forever()
# 前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>群聊</title>
</head>
<body>
<input type="text" id="send_str">
<button id="send_btn" onclick="send()">发消息</button>
<div id="chat_list">
</div>
</p>
</body>
<script type="text/javascript">
var ws = new WebSocket('ws://192.168.11.124:9009/conn_ws');
<!-- 创建连接 -->
ws.onmessage = function (messageEvent) {
console.log(messageEvent.data);
var ptag = document.createElement('p');
ptag.innerText = messageEvent.data;
document.getElementById('chat_list').appendChild(ptag);
};
function send() {
var send_str = document.getElementById('send_str').value;
ws.send(send_str);
} </script>
</html>

单聊

from flask import Flask, request, render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket
import json
app = Flask(__name__) user_socket_dict = {} # 字典 @app.route('/conn_ws/<user_nick>') #http 协议,
def ws_app(user_nick): user_socket = request.environ.get('wsgi.websocket') #type:WebSocket
user_socket_dict[user_nick] = user_socket # { 昵称:user信息 }
print(len(user_socket_dict), list(user_socket_dict.keys()))
while True: # user_socket 是一个内存地址
msg = user_socket.receive() # hang 住了
msg_dict = json.loads(msg)
to_user = msg_dict.get('to_user')
to_user_socket = user_socket_dict.get(to_user)
to_user_socket.send(msg)
print(msg) # user_socket.send(msg)
# print(request.environ.get('wsgi.websocket'))#
# --> <geventwebsocket.websocket.WebSocket object at 0x0379A9D0> ws对象
# return '555' # 遇到retur就断了
# 状态1 已经开启了
# 3 开启了,断开了 @app.route('/')
def index():
return render_template('my_ws.html') if __name__ == '__main__':
# app.run()
http_serv = WSGIServer(('0.0.0.0',9009),app,handler_class=WebSocketHandler) # 应用程序网关接口
http_serv.serve_forever()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>单聊</title>
</head>
<body>
<p><input type="text" id="nick">
<button onclick="login()">登陆聊天室</button>
</p> 发送给: <input type="text" id="to_user"> 消息: <input type="text" id="send_str"> <button id="send_btn" onclick="send()">发消息</button> <p>
<div id="chat_list">
</div>
</p>
</body>
<script type="text/javascript">
var ws = null; //公共变量, function login() {
var nick = document.getElementById('nick').value;
ws = new WebSocket('ws://192.168.11.124:9009/conn_ws/'+nick); //登录时候创建连接
ws.onmessage = function (messageEvent) { //等待消息
console.log(messageEvent.data);
var ptag = document.createElement('p');
var message = JSON.parse( messageEvent.data); ptag.innerText =message.from_user + ' : '+ message.message ;
document.getElementById('chat_list').appendChild(ptag);
};
}
function send() {
var message = document.getElementById('send_str').value;
var send_str = {
from_user:document.getElementById('nick').value,
to_user:document.getElementById('to_user').value,
message:message
};
var json_str = JSON.stringify(send_str);
ws.send(json_str);
}
// js代码是异步代码;
</script>
</html>

websocket 群聊单聊的更多相关文章

  1. websocket 群聊,单聊,加密,解密

    群聊 from flask import Flask, request, render_templatefrom geventwebsocket.handler import WebSocketHan ...

  2. Flask请求上下文源码讲解,简单的群聊单聊web

    请求上下文流程图 群聊html代码 <!DOCTYPE html> <html lang="en"> <head> <meta chars ...

  3. websocket实现群聊和单聊(转)

    昨日内容回顾 1.Flask路由 1.endpoint="user" # 反向url地址 2.url_address = url_for("user") 3.m ...

  4. WebSocket群聊与单聊

    一 . WebSocket实现群聊 py文件代码 # py文件 from flask import Flask, render_template, request from geventwebsock ...

  5. websocket 实现单聊群聊 以及 握手原理+加密方式

    WebSocket 开始代码 服务端 群聊 # type:WebSocket 给变量标注类型 # websocket web + socket from geventwebsocket.server ...

  6. flask 第五章 WebSocket GeventWebsocket 单聊群聊 握手 解密 加密

    1.WebSocket 首先我们来回顾一下,我们之前用socket学习过的项目有: 1.django 2.flask 3.FTP - 文件服务 HTTP - TCP (特点): 1.一次请求,一次响应 ...

  7. Websocket实现群聊、单聊

    Websocket 使用的第三方模块:gevent-websocket 群聊 ws群聊.py中的内容 from flask import Flask, request, render_template ...

  8. spring websocket 和socketjs实现单聊群聊,广播的消息推送详解

    spring websocket 和socketjs实现单聊群聊,广播的消息推送详解 WebSocket简单介绍 随着互联网的发展,传统的HTTP协议已经很难满足Web应用日益复杂的需求了.近年来,随 ...

  9. 基于websocket的单聊.群聊

    关于ai.baidu.com的 代码: #########################################核心代码################################### ...

随机推荐

  1. MySQL前缀索引和索引选择性

    有时候需要索引很长的字符列,这会让索引变得大且慢.通常可以索引开始的部分字符,这样可以大大节约索引空间,从而提高索引效率.但这样也会降低索引的选择性.索引的选择性是指不重复的索引值(也称为基数,car ...

  2. ansible的安装及基本使用

    1.安装ansible 如果没有版本和别的要求,这里直接使用yum安装 yum -y install ansible 查看版本 [root@ ~]#ansible --version ansible ...

  3. 009-ThreadPoolExecutor运转机制详解,线程池使用1-newFixedThreadPool、newCachedThreadPool、newSingleThreadExecutor、newScheduledThreadPool

    一.ThreadPoolExecutor理解 为什么要用线程池: 1.减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务. 2.可以根据系统的承受能力,调整线程池中工作线线程的数 ...

  4. poi 生成图片到excel

    try { InputStream iss = new FileInputStream("D:\\test.xlsx"); XSSFWorkbook wb = new XSSFWo ...

  5. vue-watch监听路由的变化

  6. Cartographer源码阅读(2):Node和MapBuilder对象

    上文提到特别注意map_builder_bridge_.AddTrajectory(x,x),查看其中的代码.两点: 首先是map_builder_.AddTrajectoryBuilder(...) ...

  7. sap 提供服务

    1: https://blog.csdn.net/stone0823/article/details/81661261?utm_source=blogxgwz1 https://blog.csdn.n ...

  8. 代码调试--自定义一个简单的debug函数

    function debug(){ $num_args = func_num_args(); //实参个数 $arg_list = func_get_args(); //返回某一个实参,必须是实参数组 ...

  9. CentOS下用yum命令安装jdk【转】

    一.使用yum命令安装 1.查看是否已安装JDK,卸载 [root@192 ~]# yum list installed |grep java java-1.8.0-openjdk.x86_64    ...

  10. 移动开发--viewport

    手机浏览器默认做了2件事情: 一.页面渲染在一个980px(ios,安卓可能有640px或1000多不等)的viewport. 二.缩放 为什么渲染时,要有viewport? 为了排版正确(980px ...