聊天室功能使用了flask来进行模板,url之类的解析,不同之处是不再使用flask自带的容器,而是当作一个应用,被gevent里的一个uwsgiserver容器来调用
前端js
// 新建一个websocket链接 var s = new WebSocket("%s://%s/foobar/"); s.onopen = function() {} // 接收后端发送过来的数据 s.onmessage = function(e) {} s.onerror = function(e) {} // s.onclose = function(e) {} // 发送数据 s.send(value);
代码只做简单实现
多人聊天室
后端:
from flask import Flask, request, render_template from geventwebsocket.websocket import WebSocket from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer import json app = Flask(__name__) @app.route("/index") def index(): return render_template("ws.html") user_socket_dict = {} @app.route("/ws/") def ws(username): user_socket = request.environ.get("wsgi.websocket") # type: WebSocket if not user_socket: return "使用WebSocket方式连接" user_socket_dict[username] = user_socket print(user_socket_dict) while True: try: # 接收客户端传入数据 user_msg = user_socket.receive() # 将以用户名为键,连接为值的字典迭代出所有的键值对 for k,v in user_socket_dict.items(): # 将当前发送数据的用户以及数据放在一起组成字典 # print(v) who_send_msg = { "send_user": username, "send_msg": user_msg } # print(who_send_msg) # 如果当前连接与迭代出来的连接相同,就跳过本次循环 if user_socket == v: continue # 否则 将用户以及用户数据以json格式发送出去 v.send(json.dumps(who_send_msg)) except Exception as e: # 当捕捉到异常的时候就将当前用户从字典中删除 user_socket_dict.pop(username)if __name__ == '__main__': http_serv = WSGIServer(("0.0.0.0",8000),app,handler_class=WebSocketHandler) http_serv.serve_forever()
前端代码:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
<style>
#chat_window{
width: 600px;
height: 400px;
border: 1px solid black;
margin: 30px auto;
}
style>
head>
<body>
<h2 style="text-align: center">聊天室h2>
<div style="text-align: center">
自报家门:<input type="text" id="username"> <button id="create_ws" onclick="go_to()">创建ws连接button>
div>
<div id="chat_window">
div>
<div style="text-align: center">
<textarea cols="75" rows="1" id="send_msg">textarea>
<button id="btn_send">发送button>
div>
body>
<script type="application/javascript">
var ws_url = "ws://127.0.0.1:8000/ws/";
var ws = null;
function go_to() {
var username = document.getElementById("username");
// 将用户参数以及url路径一起组成新的url
ws = new WebSocket(ws_url + username.value);
// console.log(ws);
// 接收后端传入的数据
ws.onmessage = function (serv_msg) {
// json反序列化出数据
msg = JSON.parse(serv_msg.data);
create_chat("y",msg);
};
}
function create_chat(self,content) {
console.log(content);
if (self == 'w'){
self = "right";
var span_tag = document.createElement("span");
span_tag.innerText = content.send_msg;
var span_tag1 = document.createElement("span");
span_tag1.innerText = ":我";
}else {
console.log(content);
self = "left";
var span_tag = document.createElement("span");
span_tag.innerText = content.send_user + ":";
var span_tag1 = document.createElement("span");
span_tag1.innerText = content.send_msg;
}
var div_tag = document.createElement("div");
div_tag.style = "text-align:" + self;
div_tag.appendChild(span_tag);
div_tag.appendChild(span_tag1);
var chat_window = document.getElementById("chat_window");
chat_window.appendChild(div_tag);
}
// 事件监听 点击发送按钮执行以下代码
document.getElementById("btn_send").addEventListener("click",function () {
// 取到输入框中数据发送
var send_msg = document.getElementById("send_msg");
ws.send(send_msg.value);
var s_msg = {send_msg:send_msg.value};
create_chat("w",s_msg);
send_msg.value = "";
})
script>
html>
一对一聊天室:
from flask import Flask, request, render_template from geventwebsocket.websocket import WebSocket from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer import json app = Flask(__name__) @app.route("/index2") def index(): return render_template("ws_one.html") user_socket_dict = {} @app.route("/ws/") def ws(username): user_socket = request.environ.get("wsgi.websocket") # type: WebSocket if not user_socket: return "使用WebSocket方式连接" user_socket_dict[username] = user_socket while True: try: # 接收客户端传入数据 user_msg = user_socket.receive() user_msg = json.loads(user_msg) to_user_socket = user_socket_dict.get(user_msg.get("to_user")) # 将当前发送数据的用户以及数据放在一起组成字典 send_msg = { "send_user": username, "send_msg": user_msg.get("send_msg") } to_user_socket.send(json.dumps(send_msg)) except WebSocketHandler as e: # 当捕捉到异常的时候就将当前用户从字典中删除 user_socket_dict.pop(username) print(e) print(user_socket_dict) if __name__ == '__main__': http_serv = WSGIServer(("0.0.0.0",8000),app,handler_class=WebSocketHandler) http_serv.serve_forever()
前端代码:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
<style>
#chat_window {
width: 600px;
height: 400px;
border: 1px solid black;
margin: 30px auto;
}
style>
head>
<body>
<h2 style="text-align: center">聊天室h2>
<div style="text-align: center">
自报家门:<input type="text" id="username">
发送目标: <input type="text" id="to_user">
<button id="create_ws" onclick="go_to()">创建ws连接button>
div>
<div id="chat_window">
div>
<div style="text-align: center">
<textarea cols="75" rows="1" id="send_msg">textarea>
<button id="btn_send">发送button>
div>
body>
<script type="application/javascript">
var ws_url = "ws://192.168.12.62:8000/ws/";
var ws = null;
function go_to() {
var username = document.getElementById("username");
// 将用户参数以及url路径一起组成新的url
ws = new WebSocket(ws_url + username.value);
// 接收后端传入的数据
ws.onmessage = function (serv_msg) {
// json反序列化出数据
msg = JSON.parse(serv_msg.data);
create_chat("y", msg);
};
}
function create_chat(self, content) {
if (self == 'w') {
self = "right";
var span_tag = document.createElement("span");
span_tag.innerText = content.send_msg;
var span_tag1 = document.createElement("span");
span_tag1.innerText = ":我";
} else {
self = "left";
var span_tag = document.createElement("span");
span_tag.innerText = content.send_user + ":";
var span_tag1 = document.createElement("span");
span_tag1.innerText = content.send_msg;
}
var div_tag = document.createElement("div");
div_tag.style = "text-align:" + self;
div_tag.appendChild(span_tag);
div_tag.appendChild(span_tag1);
var chat_window = document.getElementById("chat_window");
chat_window.appendChild(div_tag);
}
// 事件监听 点击发送按钮执行以下代码
document.getElementById("btn_send").addEventListener("click", function () {
// 取到输入框中数据发送
var send_msg = document.getElementById("send_msg");
var to_user = document.getElementById("to_user");
send_msg_json = {
send_msg:send_msg.value,
to_user:to_user.value
};
ws.send(JSON.stringify(send_msg_json));
var s_msg = {send_msg: send_msg.value};
create_chat("w", s_msg);
send_msg.value = "";
})
script>
html>