# 着重注意前段 websocket 实例的函数内作用域问题
1.websocket之群聊
1.1后端代码
代码语言:javascript复制import json
from pprint import pprint
from flask import Flask, request
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket # 做语法提示使用
app = Flask(__name__)
# websocket 的列表
user_socket_dict = {}
@app.route('/my_ws/<nick_name>')
def ws(nick_name):
print(nick_name '连接服务器')
# 记录客户端信息
user_socket = request.environ.get('wsgi.websocket') # type: WebSocket
if nick_name not in user_socket_dict:
user_socket_dict[nick_name] = user_socket
while 1:
# 收消息
msg = user_socket.receive()
for socket in user_socket_dict.values():
# 给每一个 socket 对象 send 消息
socket.send('来自用户{}-->{}'.format(nick_name, msg))
if __name__ == '__main__':
# 跟实际的 app 的原型方式不一样
print('服务启动')
http_service = WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler)
http_service.serve_forever()
1.2前段代码
代码语言:javascript复制<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-Type" 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>
</head>
<body>
<h1>websocket群聊实例</h1>
<hr id="hello">
<hr>
<p>
我的昵称: <input type="text" id="nickName">
<button id="connect">连接服务器</button>
</p>
<p>
编辑内容: <input type="text" id="chatContent">
<button id="submitContent">点击提交</button>
</p>
</body>
<script>
// 建立连接
document.getElementById('connect').onclick = function () {
let nickName = document.getElementById('nickName').value
// 定义全局新连接
ws = new WebSocket('ws://127.0.0.1:5000/my_ws/' nickName)
// 注意 ws 的作用域,在建立连接之后监听
ws.onmessage = function (data) {
// 监听获取后端的 send,组装进代码块
let msg = data.data
let htmlBlock = document.createElement("p")
htmlBlock.innerText = msg
document.getElementById('hello').appendChild(htmlBlock)
}
}
// 提交内容
document.getElementById('submitContent').onclick = function () {
let content = document.getElementById('chatContent').value
console.log(content)
// 提交内容
// 此时的 ws 已经被建立,所有可以全局函数内使用
ws.send(content)
}
</script>
</html>
2.websocket之指定好友聊天
2.1后端代码
代码语言:javascript复制import json
from pprint import pprint
from flask import Flask, request
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket # 做语法提示使用
app = Flask(__name__)
# websocket 的列表
user_socket_dict = {}
@app.route('/my_ws/<nick_name>')
def ws(nick_name):
# print(name '连接服务器')
# 记录客户端信息
user_socket = request.environ.get('wsgi.websocket') # type: WebSocket
if nick_name not in user_socket_dict:
user_socket_dict[nick_name] = user_socket
print(user_socket_dict)
while 1:
# 收消息
# 反序列化字符串
msg = json.loads(user_socket.receive())
# 取到好友名字传递信息
friend = msg['friend_name']
content = msg['content']
send_content = '来自用户{}-->{}'.format(nick_name, content)
# 给好友发一份
user_socket_dict[friend].send(send_content)
# 给自己也发一份
user_socket.send(send_content)
if __name__ == '__main__':
# 跟实际的 app 的原型方式不一样
print('服务启动')
http_service = WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler)
http_service.serve_forever()
2.2前端代码
代码语言:javascript复制<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-Type" 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>
</head>
<body>
<h1>websocket一对一实例</h1>
<hr id="hello">
<hr>
<p>
我的昵称: <input type="text" id="nickName">
<button id="connect">连接服务器</button>
</p>
<p>
发给好友: <input type="text" id="friendName">
</p>
<p>
编辑内容: <input type="text" id="chatContent">
<button id="submitContent">点击提交</button>
</p>
</body>
<script>
// 建立连接
document.getElementById('connect').onclick = function () {
let name = document.getElementById('nickName').value
// 定义全局新连接
ws = new WebSocket('ws://127.0.0.1:5000/my_ws/' name)
// 定义完连接直接监听后端数据
ws.onmessage = function (data) {
// 监听获取后端的 send,组装进代码块
let msg = data.data
let htmlBlock = document.createElement("p")
console.log('后端 msg', msg)
htmlBlock.innerText = msg
document.getElementById('hello').appendChild(htmlBlock)
}
// 提交聊天数据
document.getElementById('submitContent').onclick = function () {
// 获取想要提交的好友
let friendName = document.getElementById('friendName').value
// 获取编辑的内容
let content = document.getElementById('chatContent').value
let postMsg = {'friend_name': friendName, 'content': content}
// 提交内容
// 此时的 ws 已经被建立,所有可以全局函数内使用
ws.send(JSON.stringify(postMsg))
console.log(JSON.stringify(postMsg))
}
}
</script>
</html>