我使用NodeJS + Socket创建了一个简单的实时游戏项目。IO + Websocket + Flash。一切工作正常在我的PC(本地主机)。将项目临时放置在免费托管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(/&/, "&").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:8275",并将在传输到主机前更改
请告诉我是否更改了主机配置?作为参考,这里提供了主机和localhost的服务器日志。差异是显而易见的,但不清楚为什么会发生这种情况。
主机控制台日志:
27 Dec 09:19:49 - Cloudnode包装脚本开始(30128)在Tue Dec 27 2011 09:19:49 GMT+0100 (UTC)[36mino -] 39m插座。io开始27 Dec 09:19:49 - [INFO] Cloudnode监听端口:8275Socket-Chat监听端口8275..请访问http://:8275开始开始开始开始[90mdebug -[39m服务静态内容/socket.io.js。开始开始[90mdebug -[39m客户端授权[36minfo -[39m握手授权1357476841432378537]
本地主机控制台日志:
C: inetpub wwwroot server.js 14 l>节点信息- socket。io开始Socket-Chat监听端口8275..请访问http://:8275开始调试服务静态内容/socket.io.js开始开始开始调试-客户端授权信息握手授权3511308552126147045调试-设置请求GET/socket.io/1/flashsocket/3511308552126147045调试-设置客户端心跳间隔3511308552126147045调试-授权的客户端调试- flashsocket写1::连接
启动我的应用程序后发生握手,一切都停止了-连接失败。我改变了很多选择,但都无济于事。
我怀疑这个问题或套接字。io(但我只是复制了与我的计算机一起工作的模块)或Flash安全策略。但如何在我的特殊情况下使用它并不清楚。这里是模块,应该帮助(https://github.com/3rd-Eden/FlashPolicyFileServer),但如何将其集成到我的项目?
如果您能澄清一下,我将非常感激。
Alessioalex有点像搞定了。您的客户端代码没有利用套接字。IO来做你想做的flash socket/XHR之类的东西。您确实需要使用套接字。客户端IO:
http://socket.io/如何使用
你可能遇到的另一个问题是你的主机缺乏对WebSockets的支持。Heroku目前也有这个问题,他们建议直接使用xhr:
http://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-herokuFlashSocketPolicy集成应该非常容易。你只需要npm安装模块,把它导入到你的app.js中,然后开始监听。github repo中的示例非常简单:
https://github.com/3rd-Eden/FlashPolicyFileServer/blob/master/examples/basic.js希望这些都有帮助,快乐编码!