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