无法连接客户端和服务器import.io

时间:2016-05-14 15:40:44

标签: javascript node.js sockets

我正在开展一个用d3创建数据vizsualisation项目的个人项目。我想将数据从服务器流式传输到客户端,我将在其中进行可视化。

Idea是node.js + socket.io + d3.js

我有我的数据流,但现在我正在测试服务器数据流到客户端,使用socket.io但我经常失败。所以我用下面提到的代码采取了婴儿步骤,这也失败了。 (代码btw来自官方socket.io页面)

始终说无法找到资源文件:

Failed to load resource: The requested URL was not found on this server.
ReferenceError: Can't find variable: io

我正在玩这么多其他教程和例子,现在我完全糊涂了。任何人都可以帮忙吗?也许其他建议而不是socket.io

服务器

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3001, function(){
  console.log('listening on *:3000');
});

客户端

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>

  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>


<script>
  var socket = io();
</script>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

socket.io客户端lib可以通过CDN直接加载,如下所示:

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

但是如果你想在你的客户端独立于互联网,你需要从这里获取客户端lib http://socket.io/download/,然后将它放在服务器上的某个文件夹中,然后通过use()公开访问它以便客户端html可以获取文件,将这样的内容添加到您的应用程序:

var express = require('express');
app.use(express.static(__dirname + '/public'));

其中 public 是socket.io lib所在的目录