【问题标题】:NodeJS + Socket.IO + Websocket + Flash - transfer the project to a hostingNodeJS + Socket.IO + Websocket + Flash - 将项目转移到主机
【发布时间】:2012-01-28 09:10:31
【问题描述】:

我使用 NodeJS + Socket.IO + Websocket + Flash 创建了一个简单的实时游戏项目。在我的电脑(本地主机)上一切正常。 暂时将项目放在免费托管 cloudno.de 上。没用。

我使用这些文件: server.js - 文件服务器 nodejs(此文件未更改用于托管,因为此端口 (8275) 已通过托管指定我的应用程序):

var io = require('socket.io'),
  http = require('http');

var fs = require('fs'),
  util = require('util');

var url = require('url'),
  path = require('path'),
  mime = require('mime');

function findType(uri) {
  var ext = uri.match(/\.\w+$/gi);
  if (ext && ext.length > 0) {
    ext = ext[0].split(".")[1].toLowerCase();
    return mime.lookup(ext);
  }
  return undefined;
}

function sendError(code, response) {
  response.writeHead(code);
  response.end();
  return;
}

    var app = http.createServer(function(request, response) {
      var uri = url.parse(request.url).pathname;
      if (uri === '/') {
        uri = '/index.html';
      } else if (uri === '/server.js') {
        sendError(404, response);
        return;
      }
      var _file = path.join(process.cwd(), uri);

      path.exists(_file, function(exists) {
        if (!exists) {
          sendError(404, response);
        } else {
          fs.stat(_file, function(err, stat) {
            var file = __dirname + uri,
                type = findType(uri),
                size = stat.size;
            if (!type) {
              sendError(500, response);
            }
            response.writeHead(200, {'Content-Type':type + "; charset=utf-8", 'Content-Length':size});
            console.log("START");
            var rs = fs.createReadStream(file);
            util.pump(rs, response, function(err) {
              if (err) {
                console.log("ReadStream, WriteStream error for util.pump");
                response.end();
              }
            });
          });
        }
      });

    });

var socket = io.listen(app, {transports:['websocket', 'flashsocket', 'xhr-polling']}),
  buffer = [],
  MAXBUF = 1024,
  json = JSON.stringify;

var clients = [];
clients.usernames = function(client) {
  return client.username;
}

socket.sockets.on('connection', function(client) {
console.log("CONNECTED");
  client.on('message', function(data) {
      //skipped more line of code

  client.on('disconnect', function() {
    if (client.username) {
      client.json.broadcast.send({announcement:(client.username)+' left game', id:(client.id)});
    }
    var pos = clients.indexOf(client);
    if (pos >= 0) {
      clients.splice(pos, 1);
    }
  });});

if (!module.parent) {
  app.listen(8275);
  console.log("Socket-Chat listening on port 8275.. Go to http://<this-host>:8275");
}

index.html - 客户端文件。下面是它的一些连接Websocket的代码。

<script src="/socket.io/socket.io.js" charset="utf-8"></script>
        <script type="text/javascript" src="web_socket.js" charset="utf-8"></script>

  <script type="text/javascript"  charset="utf-8">

    // Set URL of your WebSocketMain.swf here:
    WEB_SOCKET_SWF_LOCATION = "WebSocketMain.swf";
    // Set this to dump debug message from Flash to console.log:
    WEB_SOCKET_DEBUG = true;

    // Everything below is the same as using standard WebSocket.
    var ws;

    function init() {
      // Connect to Web Socket.
      // Change host/port here to your own Web Socket server.
      ws = new WebSocket("ws://myapp.cloudno.de");//on localhost i use "localhost:8275" and will be change before transfer 
      // Set event handlers.
      ws.onopen = function() {
        output("onopen");
      };
      ws.onmessage = function(e) {
        // e.data contains received string.
        output("onmessage: " + e.data);
      };
      ws.onclose = function() {
        output("onclose");
      };
      ws.onerror = function() {
        output("onerror");
      };

    }

    function onSubmit() {
      var input = document.getElementById("input");
      // You can send message to the Web Socket using ws.send.
      ws.send(input.value);
      output("send: " + input.value);
      input.value = "";
      input.focus();
    }

    function onCloseClick() {
      ws.close();
    }

    function output(str) {
      var log = document.getElementById("log");
      var escaped = str.replace(/&/, "&amp;").replace(/</, "&lt;").
        replace(/>/, "&gt;").replace(/"/, "&quot;"); // "
      log.innerHTML = escaped + "<br>" + log.innerHTML;
    }

  </script>

web_socket.js - 脚本没有改变,完全取自项目:https://github.com/gimite/web-socket-js

WebSocketMain.swf - 这个文件没有改变,同样来自https://github.com/gimite/web-socket-js

SocketGame.swf - 这是此示例中我的游戏的主文件https://github.com/simb/FlashSocket.IO。这只改变了一行: socket = new FlashSocket("myapp.cloudno.de");//在本地主机上我使用“localhost:8275”,并且在转移到主机之前会被更改

您能否告诉我是否更改了托管配置?作为参考,托管和 localhost 的服务器日志。差异立即显而易见,但尚不清楚为什么会发生这种情况。

主机控制台日志:

12 月 27 日 09:19:49 - Cloudnode 包装脚本从 2011 年 12 月 27 日星期二 09:19:49 GMT+0100 (UTC) 开始 (30128) [36minfo -[39m socket.io 已启动 12 月 27 日 09:19:49 - [INFO] Cloudnode 监听端口:8275 Socket-Chat 监听端口 8275.. 转到 http://:8275 开始 开始 开始 开始 [90mdebug -[39m 提供静态内容 /socket.io.js 开始 开始 [90mdebug -[39m 客户端授权 [36minfo -[39m握手授权1357476841432378537

本地主机控制台日志:

C:\inetpub\wwwroot\14l>node server.js 信息 - socket.io 已启动 Socket-Chat 监听端口 8275.. 转到 http://:8275 开始 调试 - 提供静态内容 /socket.io.js 开始 开始 开始 调试 - 客户端授权 信息 - 握手授权 3511308552126147045 调试 - 设置请求 GET /socket.io/1/flashsocket/3511308552126147045 调试 - 为客户端 3511308552126147045 设置心跳间隔 调试 - 客户端授权 调试 - flashsocket 写入 1:: 已连接

启动我的应用程序后发生握手并且一切都停止 - 连接失败。我改变了很多选项 - 没有任何帮助。

我怀疑这个问题或 socket.io(但我只是复制了与我的计算机一起工作的模块)或 Flash 安全策略。但是在我的特殊情况下如何使用它还不清楚。 这是应该有帮助的模块(https://github.com/3rd-Eden/FlashPolicyFileServer),但是如何将它集成到我的项目中?

非常感谢您的澄清。

【问题讨论】:

  • 你为什么不在前端使用 Socket.IO,而是使用基本的 WS? (仅适用于 Chrome,可能还有其他 1-2 个浏览器,具体取决于设置)
  • 因为我不知道任何其他方法可以从另一个 Flash 的 Flash 客户端(移动英雄、怪物、子弹)中的 JS(Socket.IO 客户端)传递数据。 P2P 容易伪造。
  • 如果你想在 Flash 环境中使用 WebSockets,Kaazing 提供了广泛的支持。免责声明:我为 Kaazing 工作。

标签: flash node.js hosting websocket socket.io


【解决方案1】:

Alessioalex 搞定了。您的客户端代码没有利用 socket.io 来执行您想要做的闪存套接字/xhr 的事情。你真的很想在客户端使用socket.io:

http://socket.io/#how-to-use

您可能遇到的另一个问题是您的主机上缺乏对 WebSockets 的支持。 Heroku 目前正受此困扰,他们建议只使用 xhr:

http://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku

FlashSocketPolicy 集成应该非常简单。你只需要 npm install 模块,将它导入到你的 app.js 中,然后开始监听。 github repo 中的示例非常简单:

https://github.com/3rd-Eden/FlashPolicyFileServer/blob/master/examples/basic.js

希望这一切都有助于一点,快乐的编码!

【讨论】:

  • 谢谢贾斯汀。我了解了所有 nodejs 指令很多天,但这并没有帮助,因为很难学习服务器端脚本,什么时候是 flash 开发人员。我找到了这个示例 (github.com/simb/FlashSocket.IO) 并进行了聊天,有一天我创建了一个实时多人游戏,它在我的计算机上运行良好,但传输到主机时出现了问题。由于托管是免费的(我不想购买没有前景的nodejs托管),所以没有技术支持。
  • 我尝试了 FlashPolicyFileServer,但它导致 pf.listen () 行出现错误(TypeError: Object [object Object] has no method 'listen');我也试过这个解决方案github.com/freeformsystems/node-fxs。也没有结果,错误或权限被拒绝。也许这是免费托管的某种限制。至于Websockets的拒绝,我用的是Flash,不知道有什么其他的方法可以从另一个Flash的Flash客户端(移动英雄、怪物、子弹)中传递来自JS(Socket.IO客户端)的数据。
  • 嗯,很遗憾 Flash 策略模块不起作用 - 过去我不得不做一些疯狂的事情来解决这个问题,当我看到有人做了一个模块。至于将数据从 JS 传递到 Flash - 这是最简单的部分 :-) 您使用 ExternalInterface:help.adobe.com/en_US/flex/using/…
  • 这可能只是我的问题。实际上发现我的托管服务使用的 node-http-proxy 与 websockets github.com/nodejitsu/node-http-proxy/issues/97 有问题。 ExternalInterface 发送数据并接收来自 JS 的回调,但尚未看到它如何从您不等待回调的 JS 接收数据。虽然这当然很容易进行实验。谢谢。
猜你喜欢
  • 2020-03-17
  • 1970-01-01
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2016-11-19
  • 2018-07-04
  • 2022-11-22
相关资源
最近更新 更多