简体   繁体   English

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

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

I created a simple project of realtime game using NodeJS + Socket.IO + Websocket + Flash. 我使用NodeJS + Socket.IO + Websocket + Flash创建了一个简单的实时游戏项目。 Everything works fine on my PC (localhost). 在我的PC(localhost)上一切正常。 Temporarily place the project on a free hosting cloudno.de. 暂时将项目放置在免费托管的cloudno.de上。 Did not work. 不工作。

I use these files: server.js - file server nodejs (this file has not changed for hosting, because this port (8275) was nominated my application by hosting): 我使用以下文件: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 - the client file. index.html-客户端文件。 Here are some of its code to connect Websocket. 这是一些连接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 - the script has not changed and is taken entirely from the project: https://github.com/gimite/web-socket-js web_socket.js-脚本未更改,完全从项目中获取: https : //github.com/gimite/web-socket-js

WebSocketMain.swf - this file is not changed, also from https://github.com/gimite/web-socket-js WebSocketMain.swf-此文件也未更改,同样来自https://github.com/gimite/web-socket-js

SocketGame.swf - this is the main file of my game from this example https://github.com/simb/FlashSocket.IO . SocketGame.swf-这是我的游戏示例https://github.com/simb/FlashSocket.IO的主文件。 This changed only one line: socket = new FlashSocket("myapp.cloudno.de");//on localhost i use "localhost:8275" and will be change before transfer to the hosting 这仅更改了一行:socket = new FlashSocket(“ myapp.cloudno.de”); //在localhost上,我使用“ localhost:8275”,并且在转移到主机之前将被更改

Can you please tell whether I have changed the configuration for hosting? 您能告诉我是否更改了托管配置吗? For reference, the server logs for hosting and for localhost. 作为参考,服务器记录托管和本地主机。 The difference is noticeable immediately, but it is not clear why this is happening. 这种差异立即可见,但是尚不清楚为什么会发生这种情况。

Hosting console log: 主机控制台日志:

27 Dec 09:19:49 - Cloudnode wrapped script starting (30128) at Tue Dec 27 2011 09:19:49 GMT+0100 (UTC) [36minfo -[39m socket.io started 27 Dec 09:19:49 - [INFO] Cloudnode listening on port: 8275 Socket-Chat listening on port 8275.. Go to http://:8275 START START START START [90mdebug -[39m served static content /socket.io.js START START [90mdebug -[39m client authorized [36minfo -[39m handshake authorized 1357476841432378537 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 console log: Localhost控制台日志:

C:\\inetpub\\wwwroot\\14l>node server.js info - socket.io started Socket-Chat listening on port 8275.. Go to http://:8275 START debug - served static content /socket.io.js START START START debug - client authorized info - handshake authorized 3511308552126147045 debug - setting request GET /socket.io/1/flashsocket/3511308552126147045 debug - set heartbeat interval for client 3511308552126147045 debug - client authorized for debug - flashsocket writing 1:: CONNECTED 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 ::已连接

After starting my application occurs handshake and everything stopped - the connection fails. 启动我的应用程序后,发生握手并且一切都停止了-连接失败。 I changed a lot of options - nothing helps. 我改变了很多选择-没有任何帮助。

I suspect that problem or socket.io (but I simply copied the module working with my computer), or Flash security policy. 我怀疑存在问题或socket.io(但我只是复制了与计算机一起使用的模块)或Flash安全策略。 But how to use it in my particular case is not clear. 但是在我的特定情况下如何使用它尚不清楚。 Here is the module that should help (https://github.com/3rd-Eden/FlashPolicyFileServer), but how to integrate it into my project? 这是应该提供帮助的模块(https://github.com/3rd-Eden/FlashPolicyFileServer),但是如何将其集成到我的项目中呢?

I would be very grateful for the clarification. 我将不胜感激。

Alessioalex kind of nailed it. Alessioalex钉牢了它。 Your client side code isn't taking advantage of socket.io to do the flash socket / xhr stuff you're looking to do. 您的客户端代码没有利用socket.io来完成您想要做的flash socket / xhr的工作。 You really want to use socket.io on the client: 您确实想在客户端上使用socket.io:

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

The other issue you're likely to run into is a lack of support for WebSockets on your host. 您可能遇到的另一个问题是主机上对WebSockets的支持不足。 Heroku currently suffers from this, and they suggest just rolling with xhr: Heroku目前正遭受此困扰,他们建议使用xhr滚动:

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

The FlashSocketPolicy integration should be pretty easy. FlashSocketPolicy集成应该非常容易。 You just need to npm install the module, import it in your app.js, and start listening. 您只需要npm安装模块,将其导入到app.js中,然后开始监听即可。 The example in the github repo was pretty simple: github repo中的示例非常简单:

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

Hope this all helps a little, happy coding! 希望所有这些对编码有所帮助!

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

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