栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Node.js socket.io

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Node.js socket.io

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

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

因此,在上面看到,如果要绑定“套接字级别”事件(例如连接失败,断开连接等),则必须从名称空间获取 实际的套接字

ns_news.socket

// Global events are bound against socketsocket.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 pre here});

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

ns_news.send('hi there');

最后,请确保也绑定

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和socket.io之间的连接以支持websocket,需要使用Upgrade和Connection选项(来自nginx的最新版本)。这意味着您的网络服务器可以在端口80上支持网络套接字。

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/378900.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号