首页 技术 正文
技术 2022年11月14日
0 收藏 603 点赞 4,267 浏览 1598 个字

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()
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,498
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,911
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,745
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,501
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,140
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,303