可以't连接客户端和服务器import.io

can't connect client and server import.io

本文关键字:服务器 import io 客户端 连接 可以      更新时间:2023-09-26

我正在进行一个个人项目,用d3创建数据可视化项目。我想把数据从服务器流式传输到客户端,在那里我可以看到它

想法是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>

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

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

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

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

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