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

时间:2022-04-20 19:42:45

I'm relatively new to node.js and it's addons, so this is probably a beginnersquestion.

我对node比较陌生。是addons,这可能是一个初学者的问题。

I'm trying to get a simple HTML page on a webserver connect to a different server running node.js with websocket.io.

我试图在webserver上获得一个简单的HTML页面,连接到一个不同的运行节点。与websocket.io js。

My code looks like this:

我的代码是这样的:

Client

客户端

<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 + '/');

Starting up the server works fine and running http://localhost:8080 in my browser also works, returning 'Hello Socket Lover' as expected. But I want to make a different page talk to the sockets, not run one from node.js.

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

But when I run it, nothing happens and the Chrome console returns:

但当我运行它时,什么也没发生,Chrome控制台返回:

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

I've been at this all day. Any help?

我已经干了一整天了。任何帮助吗?

2 个解决方案

#1


35  

Have you tried loading the socket.io script not from a relative URL?

你试过装插座吗?io脚本不是来自相对URL吗?

You're using:

你使用:

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

And:

和:

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

You should try:

你应该试试:

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

And:

和:

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

Switch localhost:8080 with whatever fits your current setup.

切换localhost:8080,以适应当前的设置。

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

另外,根据您的设置,当从不同的域(同源策略)加载客户端页面时,您可能会遇到一些与服务器通信的问题。这可以通过不同的方式来克服(超出这个答案的范围,谷歌/SO it)。

#2


12  

You need to make sure that you add forward slash before your link to socket.io:

你需要确保你在链接到socketket.com之前添加了斜线。io:

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

Then in the view/controller just do:

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

var socket = io.connect()

That should solve your problem.

那应该能解决你的问题。

#1


35  

Have you tried loading the socket.io script not from a relative URL?

你试过装插座吗?io脚本不是来自相对URL吗?

You're using:

你使用:

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

And:

和:

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

You should try:

你应该试试:

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

And:

和:

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

Switch localhost:8080 with whatever fits your current setup.

切换localhost:8080,以适应当前的设置。

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

另外,根据您的设置,当从不同的域(同源策略)加载客户端页面时,您可能会遇到一些与服务器通信的问题。这可以通过不同的方式来克服(超出这个答案的范围,谷歌/SO it)。

#2


12  

You need to make sure that you add forward slash before your link to socket.io:

你需要确保你在链接到socketket.com之前添加了斜线。io:

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

Then in the view/controller just do:

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

var socket = io.connect()

That should solve your problem.

那应该能解决你的问题。