简体   繁体   中英

socket.io not registering when user connects

My problem here is that when someone connects to the page, it is supposed to print 'a user connected' on the command line using node.js But that message is never shown so its not registering when a user visits the page (all being done in localhost). I'll post some code below and maybe you can find the issue and help me out?

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

Replace

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

by

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

This is the correct (default) url where socket.io's client's apis are exposed (via http) by the node module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM