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');
});
res.sendFile('/opt/lampp/htdocs/testproject/index.html');
in it. I want to do it without route. – Vikas Kumarapp.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