小编God*_*tus的帖子

Websocket 连接在 Django Channels 中不起作用('WebSocket 连接到 'ws://localhost:8000/ws/board/7/' 失败:')

我正在尝试为我正在处理的 Django 项目运行一个 websocket,但我无法连接该 websocket,这很奇怪,因为我复制了示例聊天应用程序。频道文档并且工作正常,但是当我将相同的代码复制粘贴到我的项目中时,它没有工作。

因此,以下是相关代码部分:

views.py 中的相关视图

def board_view(request, key):

    board = get_object_or_404(request.user.boards, pk=key)

    key = dumps(board.pk)
    return render(request, 'core/board.html', 
            {"board":board, "permission":user_permission, "key":key})
Run Code Online (Sandbox Code Playgroud)

board.html(相关部分)

    <script>
        const key = JSON.parse("{{key|escapejs}}");

        const chatSocket = new WebSocket(
            'ws://'
            + window.location.host
            + '/ws/board/'
            + key
            + '/'
        );
Run Code Online (Sandbox Code Playgroud)

路由.py

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r"^ws/board/(?P<key>\d+)/$", consumers.ChatConsumer.as_asgi()),
]
Run Code Online (Sandbox Code Playgroud)

消费者.py

import json
from channels.generic.websocket import WebsocketConsumer


class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

        self.send(text_data=json.dumps({
            'type':'connection_established',
            'message':'you are now connected'
        }))

    def …
Run Code Online (Sandbox Code Playgroud)

django websocket python-3.x django-channels

4
推荐指数
2
解决办法
5444
查看次数

为什么 C++ 数学运算接受字母作为输入并输出数字?

我是 C++ 的新手,所以也许这是一个愚蠢的问题,但我编写了一个非常简单的温度转换程序。它看起来像这样:

#include <iostream>

int main() {
  
  double tempf;
  double tempc;
  
  // Ask the user
  std::cout << "Enter the temperature in Fahrenheit: ";
  std::cin >> tempf;
  
  // Conversion
  tempc = (tempf - 32) / 1.8;
  
  // Print Output  
  std::cout << "The temp is " << tempc << " degrees Celsius.\n";
  
}
Run Code Online (Sandbox Code Playgroud)

当我输入整数/浮点数作为输入时,它可以编译并运行良好。然而,出于好奇,我尝试输入一封信,预计会出现错误或某种失败。相反,编译后,我得到以下输出:

$ g++ temperature.cpp -o temp
$ ./temp
Enter the temperature in Fahrenheit: abc
The temp is -17.7778 degrees Celsius.
Run Code Online (Sandbox Code Playgroud)

有人能告诉我可执行文件从哪里获取输出吗-17.7778?这看起来像是一个任意数字,而不是数学输出。

c++ user-input

-2
推荐指数
1
解决办法
77
查看次数