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 command 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');
});
The socket.io library is designed to work in tandem with a node.js server, so the page the connection comes 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With