网络安全

通过websocket构建一个基础的聊天服务器

2019-08-10  本文已影响0人  字节码

https://objc.com/article/53

websocket server

基于django-private-chat 和 djangorestframework 的websockt 服务端示例

websocket client

前端示例

http://chat.enba.com
需要先登录

username password
user1 password123
user2 password123

WebSocket 的验证方式

支持jwt 和 session 两种方式对websocket进行鉴权

ws_auth_type_jwt_token = "token"
ws_auth_type_session_key = "session_key"
ws://127.0.0.1:5002/?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6IjE4OTAxMTA4NzE5IiwiZXhwIjoxNTY2Mjc2OTc2LCJlbWFpbCI6IiIsIm1vYmlsZSI6IjE4OTAxMTA4NzE5In0.IzgSstfFrDB2ehf778HHx-2Hrw6YDE54_sexFAhC9Z0&opponent=xiaoyuan
let base_ws_server_path = 'wss://chat.enba.com'
let opponent_username = 'xiaoyuan'
websocket = new WebSocket(base_ws_server_path + '?session_key={{ request.session.session_key }}' + '&opponent={{ opponent_username }}');

初始化项目

mkvirtualenv -p /usr/bin/python3 websocketserver
source ~/.virtualenvs/websocketserver/bin/activate
pip install -r requirements.txt
cd websocket_server
vim WebSocketServer/private_config.py
# 1. 创建更改的文件
python manage.py makemigrations
# 2. 将生成的py文件应用到数据库
python manage.py migrate
python manage.py createsuperuser

运行前端示例

CHAT_WS_CLIENT_HOST = '127.0.0.1'
CHAT_WS_CLIENT_PORT = 80
CHAT_WS_CLIENT_ROUTE = 'ws/'
python manage.py runserver 8000
python manage.py collectstatic --noinput

运行websocket服务端

CHAT_WS_SERVER_PROTOCOL = 'ws'
CHAT_WS_SERVER_HOST = '127.0.0.1'
CHAT_WS_SERVER_PORT = 5002
python manage.py run_chat_server

或者

cp bin/chatserver.service /lib/systemd/system

启动websocket 服务

sudo systemctl start chatserver.service

如果时修改或新建的服务文件需要先执行systemctl daemon-reload ,告诉systemd系统,然后再启动chatserver.service,不然无法正常启动。

问题

解决:
此问题是由webSocket在nginx的proxy_pass配置错误导致的,proxy_pass http://websocket_server;修改为proxy_pass http://websocket_server/;问题解决。

解决:
由于websocket服务使用python manage.py run_chat_server命令开启的,并且绑定的hostlocalhost、port为5002,通过netstat -atnp命令在本地服务器查询到5002网络端口已开启,而在阿里云ECS服务端未查询到此网络端口,期间很是郁闷,不过此时我已经找到了问题所在。此问题是由于nginx配置错误导致,在nginx的proxy_pass为127.0.0.1:5002,而websockets监听的为localhost:5002,导致反向代理失败。通过修改初始化websockets.serve()方法的host参数将localhost修改为127.0.0.1问题解决,重启chatserver.service问题解决。

Mixed Content: The page at 'https://chat.enba.com/dialogs/enba' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://chat.enba.com/ws/9ygfrczj6le3buh28b393cv20w5hzj4l/enba'. This request has been blocked; this endpoint must be available over WSS.

解决方法:

   # 此路由为websocket服务
   location /ws/ { # CHAT_WS_CLIENT_ROUTE
       # 后面必须要带`/`
       proxy_pass http://websocket_server/;
       proxy_http_version 1.1;
       proxy_connect_timeout 10s;                #配置点1
       proxy_read_timeout 60s;                  #配置点2,如果没效,可以考虑这>个时间配置长一点
       proxy_send_timeout 12s;                  #配置点3
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection "Upgrade";
   }
上一篇下一篇

猜你喜欢

热点阅读