一、群聊
服务端代码
from flask import Flask, render_template, request,Markup
from geventwebsocket.websocket import WebSocket
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
import json
app = Flask(__name__)
user_socket_dict = {}
@app.route("/")
def index():
return render_template("ql.html")
@app.route("/ws/<nickname>")
def ws(nickname):
user_socket = request.environ.get("wsgi.websocket") # type:WebSocket
if user_socket: # 如果有链接就把链接人的姓名和链接保存在字典中
user_socket_dict[nickname] = user_socket
else:
return render_template("ql.html", message = "请使用Websocket链接")
while 1:
msg = user_socket.receive() # 接受发送的消息
msg = json.loads(msg)
for us_nick_name, socket in user_socket_dict.items(): # type:WebSocket
if user_socket != socket: # 不能自己给自己发消息
try:
socket.send(json.dumps({"sender": nickname, "msg": msg["msg"]})) # 发送消息
except:
continue
if __name__ == '__main__':
http_serv = WSGIServer(("0.0.0.0", 8008), app, handler_class=WebSocketHandler)
http_serv.serve_forever()
客户端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>资源分享群</h1>
<p>{{ message }}</p>
<p>昵称:<input type="text" id="nickname">
<button onclick="createsocket()">链接群聊</button></p>
<p>消息:<input type="text" id="send_text"></p>
<button id="send" onclick="send_msg()">发送</button>
<div style="border: 2px solid; width: 500px;height: 800px;" id="text_div"></div>
<script>
var ws = null;
function createsocket() {
var nickname = document.getElementById("nickname").value; // 用户本人昵称
ws = new WebSocket("ws://127.0.0.1:8008/ws/"+nickname); // 建立Websocket链接
ws.onmessage = function (data) {
var text_div = document.getElementById("text_div");
var obj_data = JSON.parse(data.data);
var add_msg = "<p>" + obj_data.sender + ":" + obj_data.msg + "</p>" ;
text_div.innerHTML += add_msg;
}
}
function send_msg() {
var nickname = document.getElementById("nickname").value;
var msg = document.getElementById("send_text").value;
var text_div = document.getElementById("text_div");
var add_msg = "<p style='text-align: right'>" + msg + ":" + nickname + "</p>";
text_div.innerHTML += add_msg;
var msg_obj = JSON.stringify({msg:msg});
ws.send(msg_obj)
}
</script>
</body>
</html>
二、单聊
服务器代码
from flask import Flask, render_template, request,Markup
from geventwebsocket.websocket import WebSocket
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
import json
app = Flask(__name__)
user_socket_dict = {}
@app.route("/")
def index():
return render_template("ql.html")
@app.route("/ws/<nickname>")
def ws(nickname):
user_socket = request.environ.get("wsgi.websocket") # type:WebSocket
if user_socket: # 如果有链接就把链接人的姓名和链接保存在字典中
user_socket_dict[nickname] = user_socket
else:
return render_template("ql.html", message = "请使用Websocket链接")
while 1:
msg = user_socket.receive() # 接受发送的消息
msg_dic = json.loads(msg)
to_user = msg_dic.get("to_user") # 获取要发送消息的人
to_user_socket = user_socket_dict.get(to_user) # 获取要发送消息的人的链接
send_str = json.dumps({"sender":nickname,"msg":msg_dic.get("msg")})
to_user_socket.send(send_str)
if __name__ == '__main__':
http_serv = WSGIServer(("0.0.0.0", 8008), app, handler_class=WebSocketHandler)
http_serv.serve_forever()
客户端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>资源分享群</h1>
<p>{{ message }}</p>
<p>昵称:<input type="text" id="nickname">
<button onclick="createsocket()">链接群聊</button></p>
<p>与:<input type="text" id="to_user">聊天</p>
消息:<input type="text" id="send_text">
<button id="send" onclick="send_msg()">发送</button>
<div style="border: 2px solid; width: 500px;height: 800px;" id="text_div"></div>
<script>
var ws = null;
function createsocket() {
var nickname = document.getElementById("nickname").value; // 用户本人昵称
ws = new WebSocket("ws://127.0.0.1:8008/ws/"+nickname); // 建立Websocket链接
ws.onmessage = function (data) {
var text_div = document.getElementById("text_div");
var obj_data = JSON.parse(data.data);
var add_msg = "<p>" + obj_data.sender + ":" + obj_data.msg + "</p>" ;
text_div.innerHTML += add_msg;
}
}
function send_msg() {
var nickname = document.getElementById("nickname").value;
var to_user = document.getElementById("to_user").value;
var msg = document.getElementById("send_text").value;
var text_div = document.getElementById("text_div");
var add_msg = "<p style='text-align: right'>" + msg + ":" + nickname + "</p>";
text_div.innerHTML += add_msg;
var msg_obj = JSON.stringify({to_user:to_user, msg:msg});
ws.send(msg_obj)
}
</script>
</body>
</html>
网友评论