websocket实现聊天室
使用的工具 flask gevent-websocket nginx python3
先来一段代码`在这里插入代码片
from flask import Flask, render_template
from geventwebsocket.websocket import WebSocket, WebSocketError
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from flask import request, redirect
from queue import Queue
from lib1 import get_key
import time
import json
import _ctypes
app = Flask(name)
user_socket_dict3 = {}
@app.route(’/ws/chat_room/<room_id>’)
def ws(room_id):
if not send_msg_queue_dict.get(room_id):
send_msg_queue_dict[room_id] = Queue()
user_socket=request.environ.get(“wsgi.websocket”)
if not user_socket:
return “请以WEBSOCKET方式连接”
user_agent = request.user_agent
remote_addr = request.remote_addr
key = get_key(str(user_agent)+str(remote_addr))
user_name = r.get(key)
user_socket_dict3[user_name] = user_socket
while True:
try:
socket_list = []
send_msg_queue = send_msg_queue_dict.get("room_id")
cot = send_msg_queue.get()
if not cot:
continue
msg = cot.get("msg")
from_user = cot.get("from_user")
room_id = cot.get("room_id")
if room_id == "main":
members = r.get("on_line_user")
else:
members = r.get(room_id)
data = {"from_user": from_user, "contains": msg}
for member in members:
socket_list.append(user_socket_dict3.get(member))
for socket_user in socket_list:
socket_user.send(json.dumps(data))
user_msg = json.loads(user_msg)
except EnvironmentError as e:
print(e)
if name == ‘main’:
http_serve=WSGIServer(("0.0.0.0",8070),app,handler_class=WebSocketHandler)
http_serve.serve_forever()
`
nginx的配置
配置/etc/nginx/nginx.conf
在http标签下添加
map $http_upgrade $connection_upgrade {
default upgrade;
‘’ close;
}
在/ect/nginx/conf.d/*.conf中添加
location /ws {
include uwsgi_params;
proxy_http_version 1.1; #这个是重点否则可能会不支持或者传递的数据格式会出现错误
proxy_pass http://127.0.0.1:8070;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “upgrade”;
}
那么我们配置好nginx服务启动flask服务和nginx服务既可以访问了
bug多多请多指教
###纪念我的第一篇技术博客