Websocket

使用的第三方模块:gevent-websocket

群聊

ws群聊.py中的内容

from flask import Flask, request, render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
import json
from geventwebsocket.websocket import WebSocket app = Flask(__name__) user_socket_dict = {} @app.route('/ws/<user>')
def ws(user):
# print(request.environ)
user_socket = request.environ.get('wsgi.websocket') # type:WebSocket
if user_socket:
user_socket_dict[user] = user_socket
print(len(user_socket_dict), user_socket_dict)
while 1:
msg = user_socket.receive()
print(msg) # b"{from_user:jinwangba ,to_user:yinwangba,msg:"doushidawangba"}"
msg_dict = json.loads(msg)
to_usocket = user_socket_dict.get(msg_dict.get('to_user'))
to_usocket.send(json.dumps({'from_user': user, 'to_user': msg_dict.get('to_user'), 'msg': msg_dict.get('msg')})) @app.route('/')
def index():
return render_template('ws.html') if __name__ == '__main__':
# app.run('0.0.0.0', 5000, debug=True)
http_serv = WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
http_serv.serve_forever()

ws群聊.html中的内容

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>发送内容:<input type="text" id="message"><button onclick="send_msg()">发送消息</button></p>
<div id="msg_list" style="width: 500px"> </div>
</body>
<script type="application/javascript">
var ws = new WebSocket('ws://192.168.12.11:5000/ws'); ws.onmessage = function (ws_status) {
console.log(ws_status.data);
var ptag = document.createElement('p');
ptag.innerText = ws_status.data;
document.getElementById('msg_list').appendChild(ptag);
}; function send_msg() {
var msg = document.getElementById('message').value;
var ptag = document.createElement('p');
ptag.style.cssText = 'text-align: right;';
ptag.innerText = msg;
document.getElementById('msg_list').appendChild(ptag);
ws.send(msg);
{#console.log('成功');#}
}
</script>
</html>

单聊

ws.py中的内容

from flask import Flask, request, render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
import json
from geventwebsocket.websocket import WebSocket app = Flask(__name__) user_socket_dict = {} @app.route('/ws/<user>')
def ws(user):
# print(request.environ)
user_socket = request.environ.get('wsgi.websocket') # type:WebSocket
if user_socket:
user_socket_dict[user] = user_socket
print(len(user_socket_dict), user_socket_dict)
while 1:
msg = user_socket.receive()
print(msg) # b"{from_user:jinwangba ,to_user:yinwangba,msg:"doushidawangba"}"
msg_dict = json.loads(msg)
to_usocket = user_socket_dict.get(msg_dict.get('to_user'))
to_usocket.send(json.dumps({'from_user': user, 'to_user': msg_dict.get('to_user'), 'msg': msg_dict.get('msg')})) @app.route('/')
def index():
return render_template('ws.html') if __name__ == '__main__':
# app.run('0.0.0.0', 5000, debug=True)
http_serv = WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
http_serv.serve_forever()

ws.html中的内容

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Title</title>
</head>
<body>
<p>您的昵称: <input type="text" id="nick"><button onclick="openws()">进入聊天室</button></p>
{#<p>发送内容:<input type="text" id="message"><button onclick="send_msg()">发送消息</button></p>#}
<p>给<input type="text" id="to_user">发送: <input type="text" id="message"><button onclick="send_msg()">发送消息</button></p>
<div id="msg_list" style="width: 500px"> </div>
</body>
<script type="application/javascript">
var ws = null; function openws() {
var nick = document.getElementById('nick').value;
ws = new WebSocket('ws://192.168.12.11:5000/ws/' + nick);
ws.onmessage = function (ws_status) {
console.log(ws_status.data);
var msg_obj = JSON.parse(ws_status.data);
var ptag = document.createElement('p');
ptag.innerText = msg_obj.from_user + " : " + msg_obj.msg;
document.getElementById('msg_list').appendChild(ptag);
};
} function send_msg() {
var msg = document.getElementById('message').value;
var from_user = document.getElementById('nick').value;
var to_user = document.getElementById('to_user').value;
var ptag = document.createElement('p');
ptag.style.cssText = 'text-align: right;';
ptag.innerText = msg + " : " + from_user;
document.getElementById('msg_list').appendChild(ptag);
var msg_obj = {
msg: msg,
from_user: from_user,
to_user: to_user,
};
ws.send(JSON.stringify(msg_obj));
{#console.log('成功');#}
}
</script>
</html>  

websocket握手信息及封包解包原理

import socket
import base64
import hashlib #封包
def send_msg(conn, msg_bytes):
"""
WebSocket服务端向客户端发送消息
:param conn: 客户端连接到服务器端的socket对象,即: conn,address = socket.accept()
:param msg_bytes: 向客户端发送的字节
:return:
"""
import struct token = b"\x81"
length = len(msg_bytes)
if length < 126:
token += struct.pack("B", length)
elif length <= 0xFFFF:
token += struct.pack("!BH", 126, length)
else:
token += struct.pack("!BQ", 127, length) msg = token + msg_bytes
conn.send(msg)
return True def get_headers(data):
"""
将请求头格式化成字典
:param data:
:return:
"""
header_dict = {}
data = str(data, encoding='utf-8') header, body = data.split('\r\n\r\n', 1)
header_list = header.split('\r\n')
for i in range(0, len(header_list)):
if i == 0:
if len(header_list[i].split(' ')) == 3:
header_dict['method'], header_dict['url'], header_dict['protocol'] = header_list[i].split(' ')
else:
k, v = header_list[i].split(':', 1)
header_dict[k] = v.strip()
return header_dict sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('127.0.0.1', 8002))
sock.listen(5) conn, address = sock.accept()
data = conn.recv(1024)
headers = get_headers(data) # 提取请求头信息
# 对请求头中的sec-websocket-key进行加密
response_tpl = "HTTP/1.1 101 Switching Protocols\r\n" \
"Upgrade:websocket\r\n" \
"Connection: Upgrade\r\n" \
"Sec-WebSocket-Accept: %s\r\n" \
"WebSocket-Location: ws://%s%s\r\n\r\n"
magic_string = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
value = headers['Sec-WebSocket-Key'] + magic_string
ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest())
response_str = response_tpl % (ac.decode('utf-8'), headers['Host'], headers['url'])
# 响应【握手】信息
conn.send(bytes(response_str, encoding='utf-8')) # b'\x81\x87\xbe0\xb4\xc7\xc7Q\xda\xab\xd1^\xd3'
# msg[1] & 127
#
# 10100011
# 01111111
# 00100011 <= 125 # \x81\x87 \xbe0\xb4\xc7\xc7Q \xda\xab\xd1^\xd3'
# 00100011 == 126 # \x81\x87\xbe0\xb4 \xc7\xc7Q\xda\xab \xd1^\xd3'\xbe0\xb4\xc7\xc7Q\xda\xab\xd1^\xd3'
# 00100011 == 127 # \x81\x87 + 8个字节 内容
# mask
# for i in \xc7Q \xda\xab\xd1^\xd3':
# \xc7Q mask #解包
while True:
info = conn.recv(8096)
print('收到数据',info) payload_len = info[1] & 127
if payload_len == 126:
extend_payload_len = info[2:4]
mask = info[4:8]
decoded = info[8:]
elif payload_len == 127:
extend_payload_len = info[2:10]
mask = info[10:14]
decoded = info[14:]
else:
extend_payload_len = None
mask = info[2:6]
decoded = info[6:] bytes_list = bytearray()
for i in range(len(decoded)):
chunk = decoded[i] ^ mask[i % 4]
bytes_list.append(chunk)
body = str(bytes_list, encoding='utf-8')
print(body) send_msg(conn,b'nononononono') conn.close()

  

Websocket实现群聊、单聊的更多相关文章

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

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

  2. websocket 群聊单聊

    websocket 介绍 介绍引自 https://segmentfault.com/a/1190000012709475 群聊 from flask import Flask, request, r ...

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

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

  4. flask + websocket实现简单的单聊和群聊

    单聊 from flask import Flask,request,render_template from geventwebsocket.handler import WebSocketHand ...

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

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

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

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

  7. WebSocket群聊与单聊

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

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

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

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

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

随机推荐

  1. Android将Log写入文件

    为什么要将Log写入文件 运行应用程序的时候,大多数是不会连接着IDE的: 而当应用程序崩溃时,我们需要收集复现步骤,在设备上复现,并进行Debug: 而由于Android手机的多样性,有些问题是某个 ...

  2. 怎样消除adobe flash player设置

    在有FLASH画面上,点右键选下面的设置,出现设置框去掉打上钩的即可. 如果flash player插件安装好后,视频仍无法播放,则进行以下操作:打开“我的电脑”——>“本地磁盘(C)” ——& ...

  3. hadoop的client搭建-即集群外主机访问hadoop

    1增加主机映射(与namenode的映射一样): 增加最后一行  [root@localhost ~]# su - root1 [root@localhost ~]# vi /etc/hosts 12 ...

  4. antd-mobile使用报错

    在第一次使用时,按照官网的进行配置,完了报错找不到antd-mobile下面的css 解决方法来源于 :https://github.com/ant-design/ant-design-mobile/ ...

  5. ubuntu-14.04中/boot分区不足的解决办法

    环境:ubuntu-kylin 或者 ubuntu-14.04,/boot单独分区工具:ubuntu的liveCD. 问题: 由于当初安装的时候,看网上说/boot很小,100M足以,于是单独分区,分 ...

  6. CSS样式学习-1

    一.分类 ①内联,写在标签中,写法是style="样式属性".优先级最高. 优点:控制精确.缺点:代码重用性差,范围小. 例如: <div style="font- ...

  7. android的特点有哪些

    android拥有完善的应用程序框架,支持4大应用组件activity,service,contentProvider,broadcast,可以在任意层次上进行复用和更换: android中java字 ...

  8. UI5-学习篇-16-云端SCP-Destination配置

    1.登录路径: https://account.ap1.hana.ondemand.com/#/home/welcome 2.查看云连接器 如下图所示,虚拟主机都已连接且资源可用: 若虚拟主机连接存在 ...

  9. dubbo 搭建以及使用笔记

    公司使用dubbo做为rpc框架,有必要简单学习一番(自己搭建),自己做下学习记录. dubbo认识: dubbo是分布式SOA(面向服务)架构的rpc服务治理框架.可兼容各种rpc,强势的地方主要还 ...

  10. Erlang Error Records

    1.No match of right hand value ... Erlang变量名需要以大写开头.