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
后面我发现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
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
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()