草庐IT

Node.js socket.io-client connect_failed/connect_error 事件

coder 2023-05-29 原文

我在玩 node.js 和 socket.io-client。我正在尝试连接到不存在的 channel 以触发事件“connect_failed”(在 https://github.com/LearnBoost/socket.io-client 中指定)。

但是我无法让事件正常进行:

var clientio = require('socket.io-client');
console.log('Trying stuff ...');

// the channel does not exist
var socket = clientio.connect( 'http://localhost:4000/news' );

// I expect this event to be triggered
socket.on('connect_error', function(){
    console.log('Connection Failed');
});
socket.on('connect', function(){
    console.log('Connected');
});
socket.on('disconnect', function () {
  console.log('Disconnected');
});
socket.send('hi there');

如果我执行会发生这种情况:

$ node tmp_clientio.js 
Trying stuff ...

关于如果连接到不存在的 channel 时如何触发错误的任何想法?

更新:将 connect_failed 重命名为 connect_error

最佳答案

我遇到了同样的问题。我也遇到过命名空间模式开启和关闭之间存在未记录的差异,最后我不得不使用 chrome 调试器来解决。

// Bind to the news namespace, also get the underlying socket
var ns_news = clientio.connect( 'http://localhost:4000/news' );
var socket = ns_news.socket

因此,您在上面看到,如果您想绑定(bind)“套接字级别”事件(例如连接失败),则必须从命名空间中获取 实际套接字 ns_news.socket ,断开连接等

// Global events are bound against socket
socket.on('connect_failed', function(){
    console.log('Connection Failed');
});
socket.on('connect', function(){
    console.log('Connected');
});
socket.on('disconnect', function () {
  console.log('Disconnected');
});


// Your events are bound against your namespace(s)
ns_news.on('myevent', function() {
    // Custom event code here
});

请注意,您现在使用 ns_news 发送或接收事件

ns_news.send('hi there');

最后,一定要绑定(bind) socket.on('error', ...) 事件 - 如果端口不可用,它会发生

完全实现 8080 连接并回退到端口 80

我在我的实现中这样做了(尝试端口 8080,如果失败,通过 nginx 尝试端口 80)

socket_port = 8080;

ns_dash = io.connect("http://your.gridspy.co.nz/dash", {
  port: socket_port,
  'connect timeout': 5000,
  'flash policy port': 10843
});

socket = ns_dash.socket;

try_other_port = function() {
  if (socket_port !== 80) {
    if (typeof console !== "undefined" && console !== null) {
      console.log("Trying other port, instead of port " + socket_port + ", attempting port 80");
    }
    socket_port = 80;
    socket.options.port = socket_port;
    socket.options.transports = ['htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'];
    return socket.connect();
  } else {
    return typeof console !== "undefined" && console !== null ? console.log("No other ports to try.") : void 0;
  }
};
socket.on('connect_failed', function() {
  if (typeof console !== "undefined" && console !== null) {
    console.log("Connect failed (port " + socket_port + ")");
  }
  return try_other_port();
});
socket.on('error', function() {
  if (typeof console !== "undefined" && console !== null) {
    console.log("Socket.io reported a generic error");
  }
  return try_other_port();
});

我还添加了一个 nginx proxy_pass 规则,看起来像这样

location ~ ^/(socket.io)/ {
    proxy_pass http://127.0.0.1:8080;
    proxy_http_version 1.1;
    proxy_set_header Host $http_host;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
}

这里的升级和连接选项(来自 nginx 的更新版本)是升级 nginx 和 socket.io 之间的连接以支持 websockets 所必需的。这意味着您的网络服务器可以支持端口 80 上的 websocket。

此外,如果您的服务器支持 ssl/https,这将代理 wss,这是 websockets 的安全版本。

关于Node.js socket.io-client connect_failed/connect_error 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8588689/

有关Node.js socket.io-client connect_failed/connect_error 事件的更多相关文章

  1. ruby-on-rails - Ruby on Rails : . 常量化 : wrong constant name error? - 2

    我正在使用这个:4.times{|i|assert_not_equal("content#{i+2}".constantize,object.first_content)}我之前声明过局部变量content1content2content3content4content5我得到的错误NameError:wrongconstantnamecontent2这个错误是什么意思?我很确定我想要content2=\ 最佳答案 你必须用一个大字母来调用ruby​​常量:Content2而不是content2。Aconstantnamestart

  2. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  3. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  4. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  5. ruby - RVM "ERROR: Unable to checkout branch ."单用户 - 2

    我在新的Debian6VirtualBoxVM上安装RVM时遇到问题。我已经安装了所有需要的包并使用下载了安装脚本(curl-shttps://rvm.beginrescueend.com/install/rvm)>rvm,但以单个用户身份运行时bashrvm我收到以下错误消息:ERROR:Unabletocheckoutbranch.安装在这里停止,并且(据我所知)没有安装RVM的任何文件。如果我以root身份运行脚本(对于多用户安装),我会收到另一条消息:Successfullycheckedoutbranch''安装程序继续并指示成功,但未添加.rvm目录,甚至在修改我的.bas

  6. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  7. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  8. ruby-on-rails - 尝试设置 Amazon 的 S3 存储桶 : 403 Forbidden error & setting permissions - 2

    我正在关注Hartl的railstutorial.org并已到达11.4.4:Imageuploadinproduction.我做了什么:注册亚马逊网络服务在AmazonIdentityandAccessManagement中,我创建了一个用户。用户创建成功。在AmazonS3中,我创建了一个新存储桶。设置新存储桶的权限:权限:本教程指示“授予上一步创建的用户读写权限”。但是,在存储桶的“权限”下,未提及新用户名。我只能在每个人、经过身份验证的用户、日志传送、我和亚马逊似乎根据我的名字+数字创建的用户名之间进行选择。我已经通过选择经过身份验证的用户并选中了上传/删除和查看权限的框(而不

  9. ruby-on-rails - gem install rmagick -v 2.13.1 错误 Failed to build gem native extension on Mac OS 10.9.1 - 2

    我已经通过提供MagickWand.h的路径尝试了一切,我安装了命令工具。谁能帮帮我?$geminstallrmagick-v2.13.1Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingrmagick:ERROR:Failedtobuildgemnativeextension./Users/ghazanfarali/.rvm/rubies/ruby-1.8.7-p357/bin/rubyextconf.rbcheckingforRubyversion>=1.8.5...yescheckingfor/

  10. ruby 单元测试 : run some code after each failed test - 2

    在Test::Unit中的ruby​​单元测试断言失败后,在执行teardown之前,是否有一些简洁优雅的方法来立即执行我的代码?我正在做一些自动化的GUI测试,并希望在出现问题后立即截图。 最佳答案 如果您使用的是1.9,请不要使用Test::Unit::TestCase作为您的基类。对其进行子类化并覆盖#run_test以进行救援,截取屏幕截图并重新提出:classMyAbstractTestCase或者,我认为这实际上是最简洁的方法,您可以使用before_teardownHook:classMyTestCase这不适用于1.

随机推荐