You don't need express to get started with socket.io
Sadick
Posted on August 8, 2018
The best place to get started with socket.io is their website. But once you access it you are given this example app demonstrating how to use socket.io.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
If you are fairly new to node, this makes you think that express is needed in order to use socket.io. In the above example they include express to serve the index file which will be client app for your socket server. There is nothing wrong with the above approach but if lets say you don't know express, now you have one more thing to learn before using socket.io.
It would be better if they didn't introduce an additional library in their example. Socket.io has another example using the node http server
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
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(data);
});
}
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
But even this is a little bit too much. I prefer having the server and the client seperate. Therefore this would be my server.
const io = require("socket.io");
const server = io.listen(3000);
server.on("connection", function(socket) {
console.log("user connected");
socket.emit("welcome", "welcome man");
});
And the client would include the socket.io client library and just plain html.
<html>
<head>
<title>Socket io client</title>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
var socket = io("http://localhost:3000");
// use your socket
socket.on("welcome", (message) => {
// do something with the message.
})
</script>
</head>
<body>
</body>
</html>
Posted on August 8, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.