繁体   English   中英

NodeJS + Socket.IO + Websocket + Flash-将项目转移到托管

[英]NodeJS + Socket.IO + Websocket + Flash - transfer the project to a hosting

我使用NodeJS + Socket.IO + Websocket + Flash创建了一个简单的实时游戏项目。 在我的PC(localhost)上一切正常。 暂时将项目放置在免费托管的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上,我使用“ localhost:8275”,并且在转移到主机之前将被更改

您能告诉我是否更改了托管配置吗? 作为参考,服务器记录托管和本地主机。 这种差异立即可见,但是尚不清楚为什么会发生这种情况。

主机控制台日志:

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

Localhost控制台日志:

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

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

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

我将不胜感激。

Alessioalex钉牢了它。 您的客户端代码没有利用socket.io来完成您想要做的flash socket / 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安装模块,将其导入到app.js中,然后开始监听即可。 github repo中的示例非常简单:

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

希望所有这些对编码有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM