NodeJS + Socket.IO + Websocket + Flashを使用して、簡単なリアルタイムゲームプロジェクトを作成しました。私のPC(localhost)ですべてうまく動作します。 一時的にプロジェクトを無料ホスティングのcloudno.deに配置します。動作しませんでした。NodeJS + Socket.IO + Websocket + Flash - プロジェクトをホストに転送
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: - ファイルサーバnodejs(このポート(8275)がホストすることにより自分のアプリケーションをノミネートされたので、このファイルは、ホスティングのために変更されていない) server.js:
は、私はこれらのファイルを使用します - クライアントファイル。 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(/&/, "&").replace(/</, "<").
replace(/>/, ">").replace(/"/, """); // "
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です。これは1行だけ変更されました: socket = new FlashSocket( "myapp.cloudno.de"); //ローカルホストでは "localhost:8275"を使用してホストに転送する前に変更されます
私はホスティングの設定を変更しましたか?参考のため、サーバーはホスティングとローカルホストのログを記録します。その違いはすぐに目立つが、なぜこれが起こっているのかは明らかではない。
ホスティングコンソールログ:
12月27日9時19分49秒は - [39メートルソケット - Cloudnodeは、2011年9時19分49秒GMT + 0100(UTC) [36minfo 12月27日(火)にスクリプト始まる(30128)を包ん 8275 START START START START [90mdebug://:HTTPに行く..ポート8275上の8275 ソケット-チャットリスニング:ポートをリスニング[INFO] Cloudnode - .IOは12月9時19分49秒 27を開始しました - [39m静的コンテンツを提供する/socket.io.js START START [90mdebug - [39mクライアント許可 [36minfoは - [39メートルの握手は
1357476841432378537を許可ローカルホストのコンソールログ:
C:\のinetpub \ wwwrootの\ 14リットル>ノードserver.js 情報 - socket.ioは、ポート8275上の ソケット・チャットリスニングを開始しました。 。HTTPに行く://:8275 START デバッグ - START START デバッグを開始 静的コンテンツ/socket.io.jsを務めた - 設定要求GETの/socket.io - 握手3511308552126147045 デバッグを許可 - クライアントが 情報が認可しました/ 1/flashsocket/3511308552126147045 デバッグ - デバッグ用に認可クライアント - - クライアント3511308552126147045 デバッグのための設定ハートビート間隔の接続が失敗した - 私のアプリケーションを起動した後
をCONNECTED 1 :: を書いflashsocketは握手して、すべてが停止して起こります。私は多くのオプションを変更しました。何も助けません。
問題またはソケットと思われます。io(ただし、私は単に自分のコンピュータで動作するモジュールをコピーしました)、またはフラッシュセキュリティポリシー。しかし、私の特定のケースでそれを使用する方法は明確ではありません。 (https://github.com/3rd-Eden/FlashPolicyFileServer)に役立つモジュールですが、それを私のプロジェクトに統合する方法は?
私は説明のために非常に感謝します。
なぜフロントエンドでSocket.IOを使用していませんが、代わりに基本的なWSを使用していますか? (これはChromeでのみ動作し、設定に応じて別の1-2のブラウザでも動作します) – alessioalex
私はJS(Socket.IOクライアント)のデータをFlashクライアント(ムービーヒーロー、モンスター、別のフラッシュから。偽造しやすいP2P。 – Astraport
Flash環境からWebSocketを使用する場合は、[Kaazing](http://kaazing.com)が幅広くサポートしています。免責事項:私はKaazingのために働いています。 –