socket.io在用户连接时没有注册

时间:2014-09-27 23:44:06

标签: javascript node.js sockets socket.io

我的问题是,当有人连接到页面时,应该使用node.js在命令行上打印'a user connected'但是该消息从未显示,因此当用户访问页面时它不会注册(一切都在localhost完成)。我将在下面发布一些代码,也许您可​​以找到问题并帮助我解决问题?

JSON:

{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
    "express": "^4.9.5",
    "socket.io": "^1.1.0"
  }
}

HTML:

<!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="/Users/kavehkhorram/Desktop/chat-example/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>
    <script>var socket = IO();</script>
  </body>
</html>

JS:

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


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

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

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

1 个答案:

答案 0 :(得分:1)

替换

<script src="/Users/kavehkhorram/Desktop/chat-example/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>

通过

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

这是正确的(默认)url,其中socket.io的客户端的api由节点模块公开(通过http)。