flask nginx gevent-wesocket 实现聊天室

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多多请多指教
###纪念我的第一篇技术博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值