草庐IT

python - WebSocket:WebSocket 握手期间出错:已发送非空 'Sec-WebSocket-Protocol' header 但未收到响应

coder 2023-08-16 原文

我正在尝试与我的 tornado 服务器建立 WS 连接。服务器代码很简单:

class WebSocketHandler(tornado.websocket.WebSocketHandler):

    def open(self):
        print("WebSocket opened")

    def on_message(self, message):
        self.write_message(u"You said: " + message)

    def on_close(self):
        print("WebSocket closed")

def main():

    settings = {
        "static_path": os.path.join(os.path.dirname(__file__), "static")
    }


    app = tornado.web.Application([
            (r'/ws', WebSocketHandler),
            (r"/()$", tornado.web.StaticFileHandler, {'path':'static/index.html'}),
        ], **settings)


    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

我从 here 复制粘贴了客户端代码:

$(document).ready(function () {
    if ("WebSocket" in window) {

        console.log('WebSocket is supported by your browser.');

        var serviceUrl = 'ws://localhost:8888/ws';
        var protocol = 'Chat-1.0';
        var socket = new WebSocket(serviceUrl, protocol);

        socket.onopen = function () {
            console.log('Connection Established!');
        };

        socket.onclose = function () {
            console.log('Connection Closed!');
        };

        socket.onerror = function (error) {
            console.log('Error Occured: ' + error);
        };

        socket.onmessage = function (e) {
            if (typeof e.data === "string") {
                console.log('String message received: ' + e.data);
            }
            else if (e.data instanceof ArrayBuffer) {
                console.log('ArrayBuffer received: ' + e.data);
            }
            else if (e.data instanceof Blob) {
                console.log('Blob received: ' + e.data);
            }
        };

        socket.send("Hello WebSocket!");
        socket.close();
    }
});

当它尝试连接时,我在浏览器的控制台上得到以下输出:

WebSocket connection to 'ws://localhost:8888/ws' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received

这是为什么?

最佳答案

正如 whatwg.org's Websocket documentation 中指出的那样(这是标准草案的副本):

The WebSocket(url, protocols) constructor takes one or two arguments. The first argument, url, specifies the URL to which to connect. The second, protocols, if present, is either a string or an array of strings. If it is a string, it is equivalent to an array consisting of just that string; if it is omitted, it is equivalent to the empty array. Each string in the array is a subprotocol name. The connection will only be established if the server reports that it has selected one of these subprotocols. The subprotocol names must all be strings that match the requirements for elements that comprise the value of Sec-WebSocket-Protocol fields as defined by the WebSocket protocol specification.

您的服务器使用空的 Sec-WebSocket-Protocol header 响应 websocket 连接请求,因为它不支持 Chat-1 子协议(protocol)。

由于您正在编写服务器端和客户端(除非您编写的 API 是您打算共享的),因此设置特定的子协议(protocol)名称应该不是特别重要。

您可以通过从 javascript 连接中删除子协议(protocol)名称来解决此问题:

var socket = new WebSocket(serviceUrl);

或者修改您的服务器以支持所请求的协议(protocol)。

我可以举一个 Ruby 的例子,但我不能举一个 Python 的例子,因为我没有足够的信息。

编辑(Ruby 示例)

由于我在评论中被问到,这里有一个 Ruby 示例。

此示例需要 iodine HTTP/WebSockets 服务器,因为它支持 rack.upgrade specification draft (概念详细 here )并添加了发布/订阅 API。

服务器代码可以通过终端执行,也可以作为 config.ru 文件中的 Rack 应用程序执行(从命令行运行 iodine 以启动服务器) :

# frozen_string_literal: true

class ChatClient
  def on_open client
    @nickname = client.env['PATH_INFO'].to_s.split('/')[1] || "Guest"
    client.subscribe :chat    
    client.publish :chat , "#{@nickname} joined the chat."
    if client.env['my_websocket.protocol']
      client.write "You're using the #{client.env['my_websocket.protocol']} protocol"
    else
      client.write "You're not using a protocol, but we let it slide"
    end
  end
  def on_close client
    client.publish :chat , "#{@nickname} left the chat."
  end
  def on_message client, message
    client.publish :chat , "#{@nickname}: #{message}"
  end
end

module APP
  # the Rack application
  def self.call env
    return [200, {}, ["Hello World"]] unless env["rack.upgrade?"]
    env["rack.upgrade"] = ChatClient.new
    protocol = select_protocol(env)
    if protocol
      # we will use the same client for all protocols, because it's a toy example
      env['my_websocket.protocol'] = protocol # <= used by the client
      [101, { "Sec-Websocket-Protocol" => protocol }, []]
    else
      # we can either refuse the connection, or allow it without a match
      # here, it is allowed
      [101, {}, []]
    end
  end

  # the allowed protocols
  PROTOCOLS = %w{ chat-1.0 soap raw }

  def select_protocol(env)
    request_protocols = env["HTTP_SEC_WEBSOCKET_PROTOCOL"]
    unless request_protocols.nil?
      request_protocols = request_protocols.split(/,\s?/) if request_protocols.is_a?(String)
      request_protocols.detect { |request_protocol| PROTOCOLS.include? request_protocol }
    end # either `nil` or the result of `request_protocols.detect` are returned
  end

  # make functions available as a singleton module
  extend self
end

# config.ru
if __FILE__.end_with? ".ru"
  run APP 
else
# terminal?
  require 'iodine'
  Iodine.threads = 1
  Iodine.listen2http app: APP, log: true
  Iodine.start
end

要测试代码,以下 JavaScript 应该可以工作:

ws = new WebSocket("ws://localhost:3000/Mitchel", "chat-1.0");
ws.onmessage = function(e) { console.log(e.data); };
ws.onclose = function(e) { console.log("Closed"); };
ws.onopen = function(e) { e.target.send("Yo!"); };

关于python - WebSocket:WebSocket 握手期间出错:已发送非空 'Sec-WebSocket-Protocol' header 但未收到响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34198566/

有关python - WebSocket:WebSocket 握手期间出错:已发送非空 'Sec-WebSocket-Protocol' header 但未收到响应的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  4. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  5. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  6. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  7. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  8. ruby-on-rails - 新 Rails 项目 : 'bundle install' can't install rails in gemfile - 2

    我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="

  9. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  10. ruby-on-rails - Rails 中的 NoMethodError::MailersController#preview undefined method `activation_token=' for nil:NilClass - 2

    似乎无法为此找到有效的答案。我正在阅读Rails教程的第10章第10.1.2节,但似乎无法使邮件程序预览正常工作。我发现处理错误的所有答案都与教程的不同部分相关,我假设我犯的错误正盯着我的脸。我已经完成并将教程中的代码复制/粘贴到相关文件中,但到目前为止,我还看不出我输入的内容与教程中的内容有什么区别。到目前为止,建议是在函数定义中添加或删除参数user,但这并没有解决问题。触发错误的url是http://localhost:3000/rails/mailers/user_mailer/account_activation.http://localhost:3000/rails/mai

随机推荐