简体   繁体   中英

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. Everything works fine on my PC (localhost). Temporarily place the project on a free hosting 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):

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. Here are some of its code to connect 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

WebSocketMain.swf - this file is not changed, also from 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 . 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

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

Localhost console log:

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

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. 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?

I would be very grateful for the clarification.

Alessioalex kind of nailed it. Your client side code isn't taking advantage of socket.io to do the flash socket / xhr stuff you're looking to do. You really want to use socket.io on the client:

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. Heroku currently suffers from this, and they suggest just rolling with xhr:

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

The FlashSocketPolicy integration should be pretty easy. You just need to npm install the module, import it in your app.js, and start listening. The example in the github repo was pretty simple:

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

Hope this all helps a little, happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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