我正在使用带有socket.io的nodejs进行多人游戏。
当我在运行nodejs的笔记本电脑上工作时,一切正常。我可以打开多个窗口标签,我有多个用户。
但是当我尝试从我旁边的另一台笔记本电脑连接到我的本地IP(来自节点服务器)时,我收到了socket.io的错误
"GET http://localhost:8000/socket.io/socket.io.js net::ERR_CONNECTION_REFUSED"
码
/**************************************************
** GAME INITIALISATION
**************************************************/
function init() {
// Declare the canvas and rendering context
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
// Maximise the canvas
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Initialise keyboard controls
keys = new Keys();
// Calculate a random start position for the local player
// The minus 5 (half a player size) stops the player being
// placed right on the egde of the screen
var startX = Math.round(Math.random()*(canvas.width-5)),
startY = Math.round(Math.random()*(canvas.height-5));
// Initialise the local player
localPlayer = new Player(startX, startY);
socket = io.connect("http://localhost", {port: 8000, transports: ["websocket"]});
remotePlayers = [];
// Start listening for events
setEventHandlers();
};
已添加代码
/**************************************************
** NODE.JS REQUIREMENTS
**************************************************/
var util = require("util"), // Utility resources (logging, object inspection, etc)
io = require("socket.io"); // Socket.IO
Player = require("./Player").Player; // Player class
/**************************************************
** GAME VARIABLES
**************************************************/
var socket, // Socket controller
players; // Array of connected players
/**************************************************
** GAME INITIALISATION
**************************************************/
function init() {
// Create an empty array to store players
players = [];
socket = io.listen(8000);
socket.configure(function()
{
socket.set("transports", ["websocket"]);
socket.set("log level", 2);
});
setEventHandlers();
};
答案 0 :(得分:3)
我重新尝试将localhost替换为运行nodejs服务器的PC的IP地址,但它确实有效。
答案 1 :(得分:-1)
以下是我为socket.io设置工作节点服务器的方法。也许这会有所帮助。
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static(__dirname + '/'));
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
// on connection from the client this is where you can do stuff like...
//socket.emit('message', JSON.stringify(yourdataobj));
}
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
然后,在客户端html(您在上面提供的index.html)中,以下是关键行。
在头部:
<script src="/socket.io/socket.io.js"></script>
在关闭正文标记之前:
<script>
var socket = io();
socket.on('message', function(msg){
console.log(msg);
});
</script>
另外,请返回socket.io网站以获取有关如何设置所有内容的提醒和复习:http://socket.io/get-started/chat/