使用Socket.io将客户端连接到服务器

时间:2012-03-30 15:12:06

标签: javascript html5 node.js websocket socket.io

我对node.js和它的插件都比较新,所以这可能是一个初学者问题。

我正在尝试在Web服务器上获取一个简单的HTML页面,使用websocket.io连接到运行node.js的其他服务器。

我的代码如下所示:

客户端

<script src="socket.io/socket.io.js"></script>
<script>
    // Create SocketIO instance, connect

    var socket = new io.Socket();

    socket.connect('http://127.0.0.1:8080'); 

    // Add a connect listener
    socket.on('connect',function() {
      console.log('Client has connected to the server!');
    });
    // Add a connect listener
    socket.on('message',function(data) {
      console.log('Received a message from the server!',data);
    });
    // Add a disconnect listener
    socket.on('disconnect',function() {
      console.log('The client has disconnected!');
    });

    // Sends a message to the server via sockets
    function sendMessageToServer(message) {
      socket.send(message);
    };
</script>

了Serverside

// Require HTTP module (to start server) and Socket.IO
var http = require('http');
var io = require('socket.io');
var port = 8080;

// Start the server at port 8080
var server = http.createServer(function(req, res){ 
    // Send HTML headers and message
    res.writeHead(200,{ 'Content-Type': 'text/html' }); 
    res.end('<h1>Hello Socket Lover!</h1>');
});

server.listen(port);

// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

// Add a connect listener
socket.on('connection', function(client){ 
    console.log('Connection to client established');

    // Success!  Now listen to messages to be received
    client.on('message',function(event){ 
        console.log('Received message from client!',event);
    });

    client.on('disconnect',function(){
        clearInterval(interval);
        console.log('Server has disconnected');
    });
});

console.log('Server running at http://127.0.0.1:' + port + '/');

启动服务器工作正常,在浏览器中运行http://localhost:8080也可以正常工作,按预期返回“Hello Socket Lover”。但我想与套接字进行不同的页面对话,而不是从node.js运行一个。

但是当我运行它时,没有任何反应,Chrome控制台会返回:

Failed to load resource            http://undefined/socket.io/1/?t=1333119551736
Failed to load resource            http://undefined/socket.io/1/?t=1333119551735

我整天都在这。有什么帮助吗?

2 个答案:

答案 0 :(得分:39)

您是否尝试过不是从相对URL加载socket.io脚本?

您正在使用:

<script src="socket.io/socket.io.js"></script>

socket.connect('http://127.0.0.1:8080');

你应该尝试:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

socket.connect('http://localhost:8080');

根据您当前的设置切换localhost:8080

此外,根据您的设置,从其他域(同源策略)加载客户端页面时,您可能会遇到一些与服务器通信的问题。这可以用不同的方式克服(在这个答案的范围之外,google / SO它)。

答案 1 :(得分:14)

您需要确保在链接到socket.io之前添加正斜杠:

<script src="/socket.io/socket.io.js"></script>

然后在视图/控制器中执行:

var socket = io.connect()

这应该可以解决你的问题。