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. 이 변경된 행은 다음과 같습니다. socket = new FlashSocket ("myapp.cloudno.de"); // localhost에서 "localhost : 8275"를 사용하고 호스트로 전송하기 전에 변경됩니다.
호스팅 구성을 변경 했습니까? 참고로, 서버는 호스팅 및 localhost를 기록합니다. 그 차이는 즉시 눈에 띄는 것이지만, 왜 이것이 일어나고 있는지 명확하지 않습니다.
호스팅 콘솔 로그 :
12월 27일 9시 19분 49초은 - [39m 소켓 - Cloudnode 2011 9시 19분 49초 GMT + 0100 (UTC) [36minfo 12월 27일 화에서 스크립트 시작 (30128)를 포장 HTTP로 이동합니다 .. 8275 소켓 - 채팅 듣기 포트 8275에 : // : 8275 START START START START [90mdebug을 포트에서 수신 대기 [정보] Cloudnode - .io 십이 9시 19분 49초 27 시작 - [39 분 정적 콘텐츠 제공 /socket.io.js START 시작 [90mdebug - [39m 클라이언트 승인,451,515,[36minfo은 - [39m 핸드 셰이크
1357476841432378537 공인 로컬 호스트의 콘솔 로그 :
C : \을 Inetpub \ wwwroot에 \ 14리터> 노드 server.js 정보 - socket.io 포트 8275에 소켓 - 채팅 듣기 시작했다. . HTTP로 이동 : // : 8275 START 디버그 - START START 디버그를 시작 정적 콘텐츠 /socket.io.js를 제공 - 설정 요청 GET의 /socket.io - 핸드 셰이크 3511308552126147045 디버그 권한을 부여 - 클라이언트는 정보는 공인/1/플래시 소켓/3511308552126147045 0 디버그에 대한 권한 클라이언트 - -디버그 - 클라이언트 3511308552126147045 디버그를위한 설정 하트 비트 간격이 1 : 내 응용 프로그램을 시작한 후
연결 작성 flashsocket 것은 악수 모든 것이 정지 발생 - 연결이 실패합니다. 나는 많은 옵션을 변경했다.문제 또는 소켓으로 의심됩니다.io (하지만 컴퓨터로 작업하는 모듈을 단순히 복사했습니다) 또는 플래시 보안 정책을 사용합니다. 그러나 나의 특정한 경우에 그것을 사용하는 방법은 명확하지 않다. 다음은 (https://github.com/3rd-Eden/FlashPolicyFileServer) 도움이되는 모듈이지만 내 프로젝트에 통합하는 방법은 무엇입니까?
나는 분명히 설명해 주셔서 감사합니다.
왜 프론트 엔드에서 Socket.IO를 사용하지 않고 대신 기본 WS를 사용하고 있습니까? (크롬에서만 작동하고 설정에 따라 다른 1-2 브라우저에서 작동) – alessioalex
JS (Socket.IO 클라이언트) 데이터에서 플래시 클라이언트 (이동 영웅, 괴물, 총알)를 전달하는 다른 방법을 모르므로 다른 플래시에서 가져 왔습니다. 가짜 P2P. – Astraport
Flash 환경에서 WebSocket을 사용하려는 경우 [Kaazing] (http://kaazing.com)에서 광범위하게 지원합니다. 면책 조항 : 저는 카이징을 위해 일합니다. –