Okay, I have to type this pretty fast because I have to go to work soon. So, socket.io
is a publish-subscribe architecture, which is fancy talk for, it sends and receives messages. This is a very minimal example so, feel free to modify as you see fit.
- Node
- Express
- socket.io
This first part will require Express, which is a nice framework for declaring routes on a server.
const express = require('express');
const app = express();
Next, we will declare a root route, which does what it says on the tin. When we visit the pattern and protocol matched below, we will send this message as the response.
const rootRoute = (req, res) => {
res.send('<p>Hello world!</p>');
};
app.get('/', rootRoute);
Finally, we will set the port and listen on the port. Using a template string will make it easier for us to log that we are - in fact - listening.
const port = 6464;
app.listen(port, () => {
console.log(`Server listening on *:${port}`);
});
Now, we have to add the socket.io bits. This first part will make socket.io listen on the same instance that your server is running on.
var io = require('socket.io')(app);
Next, we want the server to listen for events. So, let's write our first EventListener. .on
allows us to actually register that EventListener on our socket.io object.
const onDisconnection = () => {
// This Event doesn't need any data.
console.log('A client has disconnected.');
};
const onConnection = (socket) => {
// We'll add any new behavior needed for a new client connecting here.
console.log('A new client has connected.');
// We'll also add the CLIENT'S disconnect event here.
// Note how we're attaching it to the client's object.
socket.on('disconnect', onDisconnection);
};
io.on('connect', onConnection);
So, now we have a prospective schema of the following:
Client Events | Server Events |
---|---|
disconnect | connect |
However, the actual client code has not been written yet. So, let's do that.
Let's write a client that can actually connect.
// if io() is called without params, it is assumed that the server that served the page is the target.
var socket = io();
Hilariously enough, this is all you need to see a back-and-forth using socket.io. So, let's wrap this in an index.html
.
<html>
<head>
<title>Socket.io Example</title>
</head>
<body>
<script src="https://unpkg.com/socket.io@2.0.0/lib/client.js"></script>
<script>
// if io() is called without params, it is assumed that the server that served the page is the target.
var socket = io();
</script>
</body>
</html>
NOTE: This will only work if you serve index.html
from the server. You can figure it out. :)
I hope this gives you a better idea of what you need to do. I can't write the code for you but I can at least point you in the right direction.