最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Socket.io connection not working - Stack Overflow

programmeradmin0浏览0评论

I'm trying to build a simple socket.io connection on localhost but it's not working.

What I expect from my code is that when I enter mand node socket.js it should console "connected" and at the same time on browser's console (I've already opened index.html page in a browser) I should see in console "Connected..." and "Some thing to show". But it's not working.

The server runs fine but I don't see data in both terminal and browser's console.

Am I doing something wrong?

Here's my code:

index.html

<html lang="en">
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://127.0.0.1:8080');
    socket.on('connect', function(data) {
        console.log("Connected...");
        socket.on("message", function(data){
            console.log(data);
        });
    });
</script>
</body>
</html>

socket.js

var express = require('express');
var app = express();

var bodyParser = require('body-parser');
app.use(bodyParser.json({type: '*/*'}));
var server = require('http').createServer(app);

var io = require('socket.io')(server);

app.use(express.static('/opt/lampp/htdocs/testproject/node_modules'));

io.on('connection', function(client) {
    console.log("connected");
   client.emit("message", "Some thing to show");
});
server.listen(8080);

My directory structure is like this:

htdocs/testproject/

..node_modules/

..index.html

..socket.js

EDIT: However, my code works when I add this in socket.js

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

I'm trying to build a simple socket.io connection on localhost but it's not working.

What I expect from my code is that when I enter mand node socket.js it should console "connected" and at the same time on browser's console (I've already opened index.html page in a browser) I should see in console "Connected..." and "Some thing to show". But it's not working.

The server runs fine but I don't see data in both terminal and browser's console.

Am I doing something wrong?

Here's my code:

index.html

<html lang="en">
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://127.0.0.1:8080');
    socket.on('connect', function(data) {
        console.log("Connected...");
        socket.on("message", function(data){
            console.log(data);
        });
    });
</script>
</body>
</html>

socket.js

var express = require('express');
var app = express();

var bodyParser = require('body-parser');
app.use(bodyParser.json({type: '*/*'}));
var server = require('http').createServer(app);

var io = require('socket.io')(server);

app.use(express.static('/opt/lampp/htdocs/testproject/node_modules'));

io.on('connection', function(client) {
    console.log("connected");
   client.emit("message", "Some thing to show");
});
server.listen(8080);

My directory structure is like this:

htdocs/testproject/

..node_modules/

..index.html

..socket.js

EDIT: However, my code works when I add this in socket.js

app.get('/home', function(req, res,next) {  
    res.sendFile(__dirname + '/index.html');
});
Share Improve this question edited Mar 3, 2017 at 9:02 Vikas Kumar asked Mar 3, 2017 at 8:38 Vikas KumarVikas Kumar 7394 gold badges7 silver badges18 bronze badges 10
  • Yup. No errors. Let me tell you something. It works when I add a get route in socket.js and write res.sendFile('/opt/lampp/htdocs/testproject/index.html'); in it. I want to do it without route. – Vikas Kumar Commented Mar 3, 2017 at 8:53
  • 1 Try changing your app.use to app.use(express.static('/opt/lampp/htdocs/testproject/')); then, that should cause the server to serve the index.html properly at least. If that still doesn't work then something very strange is happening since your socket.io code works on my node.js server. – Peter G Commented Mar 3, 2017 at 8:59
  • Well it worked when I changed the directory like yours. But it works only when I hit 127.0.0.1:8080 in browser. Why wouldn't it should any output to 127.0.0.1:8080/testproject/index.html ? – Vikas Kumar Commented Mar 3, 2017 at 9:06
  • 1 "localhost:8080/" was pointing to that folder. But, index.html was one level higher. If you take out node_modules, "localhost:8080/" points to the same folder as index.html. If it helps, it was trying to get the file "/opt/lampp/htdocs/testproject/node_modules/index.html" and failing silently since it didn't exist. – Peter G Commented Mar 3, 2017 at 9:18
  • 1 Make a new question if you have a new question, link it here if you want. Don't forget to see my below answer as well – Peter G Commented Mar 3, 2017 at 9:20
 |  Show 5 more ments

4 Answers 4

Reset to default 2

The socket.io library is designed to work in tandem with a node.js server, so the page the connection es from needs to be recognizable to the server (through a route). Otherwise, how can it send anything back? If you change the express.static statement to be app.use(express.static('/opt/lampp/htdocs/testproject/'));, you'll get an automatic route that will allow the library to do its thing properly. It's worth noting that you'll need to hit the base URL (that is, localhost:8080/ or localhost:8080/index.html) when loading your page in the future if you use this. If you change the file name then use localhost:8080/newfilename.html.

In socket.js:

var express = require('express');
var app = express();

var bodyParser = require('body-parser');
app.use(bodyParser.json({type: '*/*'}));
var server = require('http').createServer(app);

var io = require('socket.io')(server);

app.use(express.static('/opt/lampp/htdocs/testproject/'));

io.on('connection', function(client) {
    console.log("connected");
   client.emit("message", "Some thing to show");
});
server.listen(8080);

Couple of things i can suggest you to try here.

First please check if socket.io.js is loaded properly.

Second, first start the server and then hit http://localhost:8080 or http://127.0.0.1:8080

Also as far as i know you don't need to mention the host name on client side js when connecting. E.g.

instead of this

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

you can do this

 var socket = io.connect();

It is not working since you are opening the tab before you started your node application. It will request the socket.io.js file which can not be found and not will be reloaded. You need to start the server before you access the page and then it should work.

You should use options when running the server; otherwise, it doesn't work properly. Here is an example snippet from one of my projects.

  init: (httpServer) => {
    const options = {
      cors: true,
      origins: ["http://localhost:8080/"],
    };

    io = require("socket.io")(httpServer, options);
    return io;
  },

After that,

    const server = app.listen(8080);
    const io = init(server);

    io.on("connection", (socket) => {
      console.log("client connected");
    });

    io.on("disconnect", (socket) => {
      console.log(`client disconnected`);
    });
发布评论

评论列表(0)

  1. 暂无评论