Nginx+uWSIG+Django+websocket的實現

1.Django+websocket

django-websocket
dwebsocket
django-websocket是舊版的,如今已經沒有人維護,dwebsocket是新版的,推薦使用dwebsocket。html

python manage.py runserver --port 8000

用這兩個庫,django用以上的命令啓動的時候,能夠正常創建websocket鏈接的
可是若是django用uwsgi啓動,會報錯:handshake的時候返回400,即客服端不合法
dwebsocket的README.md裏面寫着能夠經過下面的修改來實現從uwsgi啓動
1.在settings.py增長WEBSOCKET_FACTORY_CLASS變量
2.修改uwsgi的啓動命令爲:python

uwsgi --http :8000 --http-websockets --processes 1  --wsgi-file django_wsgi.py --async 30 --ugreen --http-timeout 300

可是我試過以後失敗了nginx

2.Django+uwsgi+websocket

後面我發現uwsgi2.0已經提供了對websocket的支持
uwsgi文檔
DEMO:git

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)github

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開頭的三行配置web

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()
相關文章
相關標籤/搜索