javascript - 用户连接时 socket.io 未注册

标签 javascript node.js sockets socket.io

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

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

最佳答案

替换

<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>

这是 Node 模块(通过 http)公开 socket.io 客户端 api 的正确(默认)url。

关于javascript - 用户连接时 socket.io 未注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26080225/

相关文章:

sockets - peerconnection_client不显示对等体列表

javascript - 组件初始化之前 Angular 加载异步数据

javascript - Meteor 中的文件路径

javascript - 如何在 Linux 中作为守护进程运行的二进制 nodejs 应用程序中运行 exec?

node.js - Yarn 把离线包存放在哪里?

java - 如何关闭无限循环锁定的套接字?

linux - linux 套接字内核缓冲区是否交换到磁盘?

javascript - 如何强制 react 不重新渲染子项,只接收状态更改?

javascript - 如何将代码分成两个文件,并仍然使其在 Node.js 中工作?

javascript - 使用选择值更改对象属性