Reputation: 393
var app = require("http").createServer(handler); // handler defined below
var io = require("socket.io")(app);
var fs = require('fs');
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + "/index.html",
function (err, data) {
if (err) {
res.writeHead(500);
return res.end("Error loading index.html");
}
res.writeHead(200);
res.end("Hell World");
});
}
io.on('connection', function(socket){
socket.on('dataChanged', function(data){console.log("Hello World")});
})
io.emit('dataChanged', 'this is a test')
//index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('dataChanged', function(data){console.log("Hello World")});
</script>
I am trying to implement this trivial feature but it is not working.Where am i going wrong i dont see the logs. socket events are not registered.
Upvotes: 0
Views: 137
Reputation: 114
When I was trying to create a simple chat using socket.io I had a conneciton problem, I assume that you have the same problem: I've used the same io.connect('http://localhost:8080')
but later I tried using the IP address of my computer in WiFi network to connect from other devices (because localhost points to current device) - so the IP address of my computer in WiFi network was 192.168.0.103
-> io.connect('http://192.168.0.103')
or io.connect('http://192.168.1.103')
. I hope this works (the code was for Front-End side).
Upvotes: 0
Reputation: 888
Alright three things here.
1. Your res.end
is sending Hell world
but it should send data
res.end("Hell World");
should be
res.end(data);
This is because we want to display the index.html file not a hello world
2. Your index.html is calling the socket.io js file wrong
<script src="/node_modules/socket.io/socket.io.js"></script>
should be
<script src="/socket.io/socket.io.js"></script>
This is because you cannot reference a file like that because there is no logic for it in your code. socket.io does however have the logic for it and can be called this way
3. Use emit on the client side
In your index.html change this code
socket.on('dataChanged', function(data){console.log("Hello World")});
to
socket.emit('dataChanged', 'this is a test')
and remove
io.emit('dataChanged', 'this is a test')
from your nodejs file
Now you can see Hello World from your console
Upvotes: 1