简体   繁体   中英

Socket.io doesn't work

This is my server.js:

var app = require('express')();
var server = require('http').Server(app).listen(8080,function(){
 console.log('working');
  });
var io = require('socket.io')(server);

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

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

This is my index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
<script src="node_modules/socket.io-client/socket.io.js"></script>
 <script src="http://code.jquery.com/jquery-1.11.1.js"></script>


 <script>
    var socket = io();


</script>

</body>
 </html>

I think I did it correctly like in its site but when I run it on node and look at localhost:8080 I can't see 'someone connected' sentence in console.Where's the problem or what can be the problem?

I set up your code on my server but changed the script source of the index.html file to:

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

I can get it logging someone connected on the server.

This is taken from the top example on the socket.io website . I guess the file path resolution must be handled somewhere in the socket.io server source code.

See also: Can't find socket.io.js

Try this , Its working for me

Server.js(server side)

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');
  console.log(__dirname + " dir name");
});


io.on('connection', function(socket) {

  socket.on("join", function(name) {
  });

  socket.on('disconnect', function() {

  });
});

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

In client side

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

    socket.on('connect', function() {
        //connect
    });

socket.emit("join", 'user1');

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