使用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>

服务器端

// 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

我一整天都在这。 任何帮助?


你有没有尝试从相对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)。


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

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

然后在视图/控制器中做:

var socket = io.connect()

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

链接地址: http://www.djcxy.com/p/88019.html

上一篇: Connecting client to server using Socket.io

下一篇: Chrome, get selected text issue