GVKun编程网logo

AWS EC2 Ubuntu 实例(Django 通道)上的 Websocket 连接失败(aws alb websocket)

21

本篇文章给大家谈谈AWSEC2Ubuntu实例,以及Django通道上的Websocket连接失败的知识点,同时本文还将给你拓展djangouwsgiwebsocket踩坑、djangowebsock

本篇文章给大家谈谈AWS EC2 Ubuntu 实例,以及Django 通道上的 Websocket 连接失败的知识点,同时本文还将给你拓展django uwsgi websocket 踩坑、django websocket、Django WebSocket 连接到“ws://127.0.0.1:8000/ws/chat/8_9/”失败:、Django 向 WebSocket 发送数据等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

AWS EC2 Ubuntu 实例(Django 通道)上的 Websocket 连接失败(aws alb websocket)

AWS EC2 Ubuntu 实例(Django 通道)上的 Websocket 连接失败(aws alb websocket)

如何解决AWS EC2 Ubuntu 实例(Django 通道)上的 Websocket 连接失败?

我正在尝试在 ubuntu aws ec2 实例中部署我的 django chammels asgi 应用程序,我的 wsgi 应用程序运行良好,ubuntu 上的 asgi 运行良好(使用 python websocket 库测试)代码中没有错误并且 daphne 正在运行完美

我也启用了 EC2 安全组中的所有端口

enter image description here

代码库没有错误,daphne也完美运行在EC2 ubuntu实例的本地

server {
    listen 80;
    server_name MY_SERVER_IP;

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }

    location /ws/{
        proxy_pass http://0.0.0.0:4001;
        proxy_buffering off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
    }
}

[Unit]
Description=project daphne Service
After=network.target

[Service]
User=root
Type=simple
WorkingDirectory=/home/ubuntu/myproject
ExecStart=/home/ubuntu/myproject/venv/bin/python /home/ubuntu/myproject/venv/bin/d>

[Install]
WantedBy=multi-user.target

我创建了这个 python 脚本来确定我的 daphne 是否正常工作,它为我提供了完美的结果,没有错误

import asyncio
import websockets
import json
async def hello():
    uri = "ws://127.0.0.1:4001/ws/chat/person/?token=<CHAT_TOKEN>
    async with websockets.connect(uri) as websocket:
          await websocket.send(json.dumps({"message":"hey there"}))
          g = await websocket.recv()
          print(g)
asyncio.get_event_loop().run_until_complete(hello())

以下脚本返回

{
  "id": 1,"message": "hey There","time_stamp": "TIME","receiver": {
     "username": "John Doe","id": 2","profile_picture": "LINK"
  }
}

现在在我的前端应用程序中,当我尝试与 websocket 连接时

socket = new WebSocket("ws://<SERVER_IP>:4001/ws/chat/person/?token=<MY_TOKEN>")

socket.onopen = functon(){
...
}
...

但是下面的脚本返回

WebSocket connection to ''ws://<SERVER_IP>/ws/chat/person/?token=<TOKEN> Failed:

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

django uwsgi websocket 踩坑

django uwsgi websocket 踩坑

https://www.cnblogs.com/Xjng/p/4853080.html

上面的是参考内容,

我的环境如下,python2.7,django1.11,uwsgi2.0 以上,niginx 作为代理

安装 openssl: apt-get install libssl-dev, 安装完这个 uwsgi 要重新装

客户端是用的 websocket 作为发送的,pip install websocket-client, 注意不是 websocket 这两个 import 时候都是 import websocket

uwsgi.ini 中添加 http-websockets = true

重头戏出现了,不能 pip install uwsgi, 而是应该下源码 https://github.com/unbit/uwsgi, python setup.py install

def f(request):
    import uwsgi
    uwsgi.websocket_handshake()
    while True:
        msg = uwsgi.websocket_recv()
        uwsgi.websocket_send(msg)
#!/usr/bin/env python
#import socket
import websocket
import time
s = websocket.create_connection("ws://127.0.0.1:8080/xxx")
print("Sending Hello, World...")

s.send("Hello, World")
print("sent")
print("Receiving")
a = 1
while 1:
    s.send("Hello, World{:0>9d}".format(a))
    result = s.recv()
    print("Received ''%s''" % result)
    time.sleep(1)
    a += 1
s.close()

 

网址被我改了,

终于跑通了,真是不容易,连续踩坑

 

 

今天在云上部署 websocket, 直接 pip install uwsgi 竟然也可以,感觉很诡异啊

 

django websocket

django websocket

1、dwebsocket 

2、等框架都是错误的

3、  django/channels 才是正确姿势 555    

4、 

pip install -U channels 

完成后,您应该添加channels到您的 INSTALLED_APPS设置:

INSTALLED_APPS = (
    ''django.contrib.auth'', ''django.contrib.contenttypes'', ''django.contrib.sessions'', ''django.contrib.sites'', ... ''channels'', ) 

然后,在以下位置进行默认路由myproject/routing.py

from channels.routing import ProtocolTypeRouter

application = ProtocolTypeRouter({ # Empty for now (http->django views is added by default) }) 

最后,将您的ASGI_APPLICATION设置设置为指向该路由对象作为根应用程序:

ASGI_APPLICATION = "myproject.routing.application"

Django WebSocket 连接到“ws://127.0.0.1:8000/ws/chat/8_9/”失败:

Django WebSocket 连接到“ws://127.0.0.1:8000/ws/chat/8_9/”失败:

如何解决Django WebSocket 连接到“ws://127.0.0.1:8000/ws/chat/8_9/”失败:?

我正在做一个 Django 项目,其中我使用 Django 频道添加了实时聊天功能。当我完成消息传递部分后,我开始处理项目的其他部分(例如发帖、点赞帖子,以及与消息传递无关的一般部分)。但是现在当我测试消息传递页面时,我在浏览器控制台中收到以下错误:

8_9:58 WebSocket connection to ''ws://127.0.0.1:8000/ws/chat/8_9/'' Failed:

错误在冒号后没有进一步的解释(这就是为什么我什至不知道从哪里开始解决它,我也遇到过类似的错误,但冒号后总是有别的东西)。我还尝试使用 GitHub 回滚到我的应用程序的旧版本(我回到了我确定可以工作的最后一个版本),但它仍然无法工作。

这是我的js代码:

        const roomName = JSON.parse(document.getElementById(''room-name'').textContent);

        var chatSocket = "";

        if(document.location.protocol == "https:"){
            chatSocket = new WebSocket(
                ''wss://''
                + window.location.host
                + ''/wss/chat/''
                + roomName
                + ''/''
            );
        }
        else{
            chatSocket = new WebSocket(
                ''ws://''
                + window.location.host
                + ''/ws/chat/''
                + roomName
                + ''/''
            );
        }

        chatSocket.addEventListener(''open'',function(event) {
            $.ajax({
                url: ''/ajax/get_msg/'',data: {
                  ''room'': roomName
                },dataType: ''json'',success: function (data) {
                  var realData=data[0];
                  var i=0;
                  while(i<realData.length){
                    document.querySelector(''#chat-log'').value += (realData[i][0] + '': '' + realData[i][1] + ''\n'');
                    i++;
                  }
                }
            });
        })

        chatSocket.onmessage = function(e) {
            const data = JSON.parse(e.data);
            document.querySelector(''#chat-log'').value += (data.user + '': '' + data.message + ''\n'');
        };

        chatSocket.onclose = function(e) {
            console.error(''Chat socket closed unexpectedly'');
        };

        document.querySelector(''#chat-message-input'').focus();
        document.querySelector(''#chat-message-input'').onkeyup = function(e) {
            if (e.keyCode === 13) {  // enter,return
                document.querySelector(''#chat-message-submit'').click();
            }
        };

        document.querySelector(''#chat-message-submit'').onclick = function(e) {
            const messageInputDom = document.querySelector(''#chat-message-input'');
            const message = messageInputDom.value;
            chatSocket.send(JSON.stringify({
                ''message'': message,}));
            messageInputDom.value = '''';
        };

我的路由:

# Django imports
from django.urls import re_path
from . import consumers

# routing to the consumer
websocket_urlpatterns=[
    re_path(r''wss/chat/(?P<room_name>\w+)/$'',consumers.ChatConsumer),re_path(r''ws/chat/(?P<room_name>\w+)/$'',]

我的消费者:

import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from django.contrib.auth import get_user_model
from .models import Message

User = get_user_model()


class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope[''url_route''][''kwargs''][''room_name'']
        self.room_group_name = ''chat_%s'' % self.room_name
        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,self.channel_name
        )

        self.accept()

    def disconnect(self,close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,self.channel_name
        )

    # Receive message from WebSocket
    def receive(self,text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json[''message'']

        # get both users
        user = self.scope["user"]
        get_ids = self.scope["url_route"]["kwargs"]["room_name"]
        ids = get_ids.split(''_'')
        my_user = User.objects.get(username=user.username)
        my_id = my_user.id
        other_id = 0
        if str(ids[0]) == str(my_id):
            other_id = ids[1]
        else:
            other_id = ids[0]
        other_user = User.objects.get(pk=other_id)

        # save the sent message to a database
        new_message = Message(sender=my_user,rec=other_user,text=message,room=get_ids)
        new_message.save()

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,{
                ''type'': ''chat_message'',''message'': message,''user'': user.username,}
        )

    # Receive message from room group
    def chat_message(self,event):
        message = event[''message'']
        # get the user that sent the message
        user = event[''user'']
        # Send message to WebSocket
        self.send(text_data=json.dumps({
            ''message'': message,''user'': user
        }))

还有我的设置:

CACHES = {
    "default": {
         "BACKEND": "redis_cache.RedisCache","LOCATION": REdis_URI,}
}
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer","CONfig": {
            "hosts": [REdis_URI],},}

任何帮助将不胜感激

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Django 向 WebSocket 发送数据

Django 向 WebSocket 发送数据

如何解决Django 向 WebSocket 发送数据?

我有一个项目,我希望在数据库中发生更改时更新页面的内容。我已经设置了频道并且通讯效果很好(来自某些组的用户可以在他们的组内发送和接收消息 - 一切都很好)。

现在我有后台任务在数据库中的值发生变化的特定时间运行和触发。我想要做的(如果可能的话)是将一些数据发送到某个套接字(在后台工作函数内部数据库中的数据更改的函数之后发送),并且与它相关的用户将收到消息和将执行某些操作。所以我试图找到一种发送数据的方法,但不知道如何发送。

@background(schedule=30)
def room_start(room_url):
    room= Room.objects.get(room_url=room_url)
    room.state = "R"
    room.save()


   # This is where I would send some data to users and notify them of changes and perform
   # actions on the frontend according to it.
   # I''m not sure what the solution would be,but I was thinking of maybe sending test message to 
   # the socket and checking if there is an update but that doesn''t seem to be the right way to do 
   # it. I''m not sure if maybe passing the object when calling the background function Could do the 
   # trick but again that probably wouldn''t be the best way to do it


    print("ROOM STATE CHANGED TO R")

也许 websockets 甚至不是这里的解决方案,也许实施轮询之类的东西会更好,但我不确定,所以不胜感激。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

今天关于AWS EC2 Ubuntu 实例Django 通道上的 Websocket 连接失败的分享就到这里,希望大家有所收获,若想了解更多关于django uwsgi websocket 踩坑、django websocket、Django WebSocket 连接到“ws://127.0.0.1:8000/ws/chat/8_9/”失败:、Django 向 WebSocket 发送数据等相关知识,可以在本站进行查询。

本文标签: