1.Django+websocket
django-websocket
dwebsocket
django-websocket是舊版的,現在已經沒有人維護,dwebsocket是新版的,推薦使用dwebsocket。
python manage.py runserver --port 8000
用這兩個庫,django用以上的命令啟動的時候,可以正常建立websocket連接的
但是如果django用uwsgi啟動,會報錯:handshake的時候返回400,即客服端不合法
dwebsocket的README.md里面寫着可以通過下面的修改來實現從uwsgi啟動
1.在settings.py增加WEBSOCKET_FACTORY_CLASS變量
2.修改uwsgi的啟動命令為:
uwsgi --http :8000 --http-websockets --processes 1 --wsgi-file django_wsgi.py --async 30 --ugreen --http-timeout 300
但是我試過之后失敗了
2.Django+uwsgi+websocket
后面我發現uwsgi2.0已經提供了對websocket的支持
uwsgi文檔
DEMO:
def echo_once(request):
import uwsgi
uwsgi.websocket_handshake() #與客戶端建立連接 ,在uwsgi2.0中,這個函數不需要參數
while True:
msg = uwsgi.websocket_recv() #阻塞,等待客戶端發來的消息
uwsgi.websocket_send(msg) #發送消息到客服端
所有的API:
uwsgi.websocket_handshake([key, origin, proto])
uwsgi.websocket_recv()
uwsgi.websocket_send(msg)
uwsgi.websocket_send_binary(msg) (added in 1.9.21 to support binary messages)
uwsgi.websocket_recv_nb()
uwsgi.websocket_send_from_sharedarea(id, pos) (added in 1.9.21, allows sending directly from a SharedArea – share memory pages between uWSGI components)
uwsgi.websocket_send_binary_from_sharedarea(id, pos) (added in 1.9.21, allows sending directly from a SharedArea – share memory pages between uWSGI components)
3.nginx的配置:
location / {
uwsgi_pass 127.0.0.1:8000;
include uwsgi_params;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
在nginx的server中加入proxy
開頭的三行配置
4.調試用的python websocket客戶端
from websocket import create_connection
ws = create_connection("ws://192.168.000.000:8000/echo_once")
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
print "Reeiving..."
result = ws.recv()
print "Received '%s'" % result
ws.close()