【问题标题】:Can't get up and running with socket.io无法使用 socket.io 启动和运行
【发布时间】:2012-06-07 01:18:15
【问题描述】:

我在 Windows 上运行并使用 WAMP 作为 localhost 服务器。我已经搜索了很多教程,尝试了很多东西等,但仍然没有任何效果..

当前设置

现在写,在我的 www/ 目录中,我创建了一个名为 socketiodemo 的文件夹。

在其中,我做了npm install socket.io 以及安装了一些其他节点包:

  • socket.io
  • 快递
  • 笔尖
  • 手写笔

我安装了所有上述软件包,即使我实际上并不需要它们。我刚刚安装了它们,因为很多教程都需要它们,但我宁愿不使用它们,而是使用 javascript 访问纯 socket.io。

所以,这是我在 www 下的目录的快照:

  • app.js
  • index.html
  • node_modules
    • socket.io
    • 快递
    • 笔尖
    • 手写笔

我发现的最精简的教程之一给了我这个 app.js 代码,它是服务器端:

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

// 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(8080);

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

// Add a connect listener
socket.sockets.on('connection', function(client){ 

    // Create periodical which ends a message to the client every 5 seconds
    var interval = setInterval(function() {
        client.send('This is a message from the server!  ' + new Date().getTime());
    },5000);

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

});

客户端代码如下 index.html:

<!DOCTYPE html>
<html>
<head>
    <style>
        * { margin:0; padding:0; font-size:11px; font-family:arial; color:#444; }
        body { padding:20px; }
        #message-list { list-style-type:none; width:300px; height:300px; overflow:auto; border:1px solid #999; padding:20px; }
        #message-list li { border-bottom:1px solid #ccc; padding-bottom:2px; margin-bottom:5px; }
        code { font-family:courier; background:#eee; padding:2px 4px; }
    </style>
    <script src="http://cdn.socket.io/stable/socket.io.js"></script>
    <script>

        // Create SocketIO instance
        var socket = new io.Socket('localhost',{
            port: 8080
        });
        socket.connect(); 

        // Add a connect listener
        socket.on('connect',function() {
            log('<span style="color:green;">Client has connected to the server!</span>');
        });
        // Add a connect listener
        socket.on('message',function(data) {
            log('Received a message from the server:  ' + data);
        });
        // Add a disconnect listener
        socket.on('disconnect',function() {
            log('<span style="color:red;">The client has disconnected!</span>');
        });

        // Sends a message to the server via sockets
        function sendMessageToServer(message) {
            socket.send(message);
            log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
        }

        // Outputs to console and list
        function log(message) {
            var li = document.createElement('li');
            li.innerHTML = message;
            document.getElementById('message-list').appendChild(li);
        }

    </script>
</head>
<body>

    <p>Messages will appear below (and in the console).</p><br />
    <ul id="message-list"></ul>
    <ul style="margin:20px 0 0 20px;">
        <li>Type <code>socket.disconnect()</code> to disconnect</li>
        <li>Type <code>socket.connect()</code> to reconnect</li>
        <li>Type <code>sendMessageToServer('Your Message')</code> to send a message to the server</li>
    </ul>

</body>
</html>

客户端代码旨在通过在 chrome 的检查器中动态调用 sendMessageToServer('Your Message') 来工作。


电流输出

所以,是时候运行服务器了。 WAMP 上线了,去 www/socketiodemo 做

node app.js

给我输出:

info - socket.io started

现在,进入 localhost/socketiodemo,重复显示以下日志:

XMLHttpRequest cannot load http://localhost:8080/socket.io/xhr-polling//1338578840544. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

XMLHttpRequest cannot load http://localhost:8080/socket.io/xhr-polling//1338578850545. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

现在服务器(节点 app.js)开始显示以下消息:

  info  - socket.io started
  warn  - unknown transport: "undefined"
  info  - unhandled socket.io url
  warn  - unknown transport: "undefined"
  info  - unhandled socket.io url
  warn  - unknown transport: "undefined"

另外,在客户端中,sendMessageToServer('Hello'); 只是简单地附加到 ul: Sending "hello" to the server! 但实际上并没有对服务器做任何事情。服务器只是不断地转储上面的infos 和warns。客户端也不断出现上面显示的XMLHttpRequest 错误。

您能确定问题出在哪里吗?我实际上已经尝试了很多教程和东西,这是我最接近工作的地方。

如果有人还想推荐一个他们知道可行的教程,请这样做。

【问题讨论】:

标签: html node.js websocket socket.io


【解决方案1】:

随着时间的推移,一些 Socket.IO 的东西发生了变化。此外,您可能希望从同一主机/端口提供 HTML 和 Socket.IO JS。试试这个:

将您的 index.html 移动到 public 目录中

这样你就有了以下树:

app.js
public/
  index.html
node_modules/
  socket.io
  express
  (whatever else)

修改 app.js 以提供 HTML

将您的 app.js 更改为以下 JavaScript(仅前几行更改):

// Require Express module (to start server) and Socket.IO
var io = require('socket.io'), express = require('express');

var server = express.createServer();

server.use(express.static(__dirname + "/public"));

server.listen(8080);

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

// Add a connect listener
socket.sockets.on('connection', function(client){

    // Create periodical which ends a message to the client every 5 seconds
    var interval = setInterval(function() {
        client.send('This is a message from the server!  ' + new Date().getTime());
    },5000);

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

});

使用此代码,当您访问 localhost:8080 时,您的服务器将使用 Express 服务 index.html

更改您的 Socket.IO 代码

index.html 中,将&lt;script&gt; 标记更改为:&lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt;,然后将JavaScript 更改为读取(仅第一部分更改):

// Create SocketIO instance
var socket = io.connect();

// Add a connect listener
socket.on('connect',function() {
    log('<span style="color:green;">Client has connected to the server!</span>');
});
// Add a connect listener
socket.on('message',function(data) {
    log('Received a message from the server:  ' + data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
    log('<span style="color:red;">The client has disconnected!</span>');
});

// Sends a message to the server via sockets
function sendMessageToServer(message) {
    socket.send(message);
    log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
}

// Outputs to console and list
function log(message) {
    var li = document.createElement('li');
    li.innerHTML = message;
    document.getElementById('message-list').appendChild(li);
}

启动你的服务器并访问 localhost:8080

请注意,这会一起跳过 WAMP 堆栈; Node.js 为 Socket.IO 代码和你的静态文件提供服务。当您访问 localhost:8080 时,您应该会看到这些消息。另请注意,您应该使用socket.socket.disconnect() 断开连接并使用socket.socket.connect() 重新连接。

源代码

此应用程序的工作版本的源代码位于https://github.com/BinaryMuse/so-10856370;记得npm install express socket.io

【讨论】:

  • 太棒了,它奏效了。 node.js 现在服务于实际页面是一个有趣的想法。我当前项目的下一步是尝试使用它,直到我对 node.js 和 websockets 都感到满意,然后我需要某种方式来使用 node.js 与数据库进行通信。我想我必须自己做一些研究,但如果你想引导我到一些你认为可能有帮助的网站/书籍,那么我将不胜感激!!再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2017-05-07
  • 2015-07-10
  • 2018-10-30
  • 2017-07-01
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多