I've been looking for a working demo of socket.io that does not use Express.js, why doesn't this example work:
server:
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', client => {
client.on('event', data => { /* … */ });
client.on('disconnect', () => { /* … */ });
});
server.listen(3000);
client:
<script src="node_modules/socket.io/client-dist/socket.io.js"></script>
<script>
const socket = io("http://localhost");
</script>
This gives the error: polling-xhr.js:157 GET http://localhost/socket.io/?EIO=4&transport=polling&t=NwWVGV9 net::ERR_CONNECTION_REFUSED
Found something that works:
server:
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
function handler(req, res) {
var url;
if (req.url == "/") {
url = "/index.html";
} else {
url = req.url;
}
fs.readFile(__dirname + url, function (err, data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
socket.on('disconnect', function () {
console.log(socket.id + ' disconnect ('+ socket.client.conn.transport.constructor.name +')');
});
});
client:
<script src="node_modules/socket.io/client-dist/socket.io.min.js"></script>
<script>
var socket = io();
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>