【问题标题】:Not able to run basic socket.io example无法运行基本的 socket.io 示例
【发布时间】:2014-04-09 20:22:45
【问题描述】:

我有 index.html 这样的:

<script src="socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
  });
</script>

app.js 本身:

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
if (err) {
  res.writeHead(500);
  return res.end('Error loading index.html');
}

res.writeHead(200);
res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
console.log(data);
  });
});

这些文件放在 /var/www 中。

我跑了:

sudo npm install socket.io

所以,现在我有一个文件夹:/var/www/node_modules/socket.io

在我的浏览器 (chrome) 中,我输入了“localhost” - 我收到了 socket.io.js 的文件未找到错误(在 chrome 的控制台中)。所以在 index.html 中,我将 src 行修改为:

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

但后来我在其他地方(在 socket.io.js 中)发现了一个文件未找到错误:
未捕获的 ReferenceError:未定义要求

对于以下行:

var client = require('socket.io-client');

我是否只是不断更改所有这些文件的路径?
我还在以下行的 index.html 处收到“io is not defined”错误:

var socket = io.connect('http://localhost');

服务器端
当我进入终端并输入

node app.js

我收到以下错误:
信息 - socket.io 已启动
警告 - 引发错误:错误:监听 EACCES

请帮忙。谢谢。

【问题讨论】:

    标签: javascript html node.js sockets socket.io


    【解决方案1】:

    在我的例子中,我通过将端口号(因为 80 已经在使用)更改为 8000 解决了服务器端问题。

    然后我通过终端运行 app.js 并让它继续运行。

    我输入了

    http://localhost:8000/index.html 
    

    进入我的网络浏览器,一切正常。

    我什至用过:

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

    在 index.html 中。如果你让服务器先运行,浏览器就能找到所有正确的 nodejs 文件的路径。

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2021-02-09
      • 2011-10-09
      • 2012-08-27
      相关资源
      最近更新 更多