SocketIO is a javascript library that allows real-time two way communication between a client and server. Extremely useful.
- Create a new folder
- Set up npm and install dependencies
npm init
npm install express --save
npm install socket.io --save
- Install Git and NodeJS
- Clone the repo.
git clone https://github.com/hacksu/socket-penguin-club.git
- Install dependencies.
npm install
- Run the app.
node app.js
SocketIO has two main operations, sending data and recieving data.
To send data, use the emit() method passing in the name of the
of the event and the data object to send.
socket.emit('event', data);To recieve data, create an event handler using the on() method.
The first parameter should be the name of the event and the second
parameter is a function to handle the data.
socket.on('event', (data) => {
// Do operations here.
});- Save a list of all clients.
function onClientConnect(socket) {
clients.push({
conn: socket
});
console.log('clients connected: ' + clients.length);
}
function onClientDisconnect(socket) {
var numClients = clients.length;
clients = clients.filter(item => item.conn !== socket);
console.log('client disconnected ' + numClients + ' => ' + clients.length);
}
io.on('connection', (socket) => {
onClientConnect(socket);
socket.on('disconnect', () => {
onClientDisconnect(socket);
});
});- Send a message from the client.
<input onclick="sendMessage()"
value="Send a message"
type="button"
/>
...
<script>
function sendMessage() {
socket.emit('message', 'A test message');
}
</script> - Listen for a message on the server.
socket.on('message', (msg) => {
console.log(msg);
});- Forward message to all connected clients
socket.on('message', (msg) => {
for (var i = 0; i < clients.length; i++){
clients[i].conn.emit('fwd:msg', msg);
}
});- Recieve forwarded messages clientside.
<script>
...
socket.on('fwd:msg', (msg) => {
console.log(msg);
});
...
</script>- Add some resources to the head of our HTML.
<head>
...
<script src="/mechanics.js"></script>
<link rel="stylesheet" href="/style.css"></link>
</head>- Render our character on the screen.
<body>
<img src="/penguin.gif" class="penguin" id="me" />
</body>- Move our socket code into mechanics.js inside the
window.onloadcallback function.
window.onload = () => {
// Put socket code here.
};- Get a reference to our character and wire it up in the key press handlers so that he moves.
var me = penguin(document.getElementById('me'));
...
document.addEventListener('keydown', event => {
if (event.keyCode == 87){
// Up key
console.log('up');
me.up(); // <--- This line.
}
// Fill out the others too.
...- Send the move data to the server in
update().
socket.emit('move', {
xPos: x,
yPos: y
});- In the server, add a handler for the move event that sends the player number and the move to each of the other clients.
socket.on('move', (location) => {
for (var i = 0; i < clients.length; i++){
clients[i].conn.emit('fwd:move',{
player: socket.clientNum,
loc: location
} );
}
});- Listen for fowarded movements clintside and move the sprites accordingly.
socket.on('fwd:move', move => {
console.log(move);
if (me.id === move.player) return;
moveOrCreatePenguin(move);
});- Add some player ids to the server to keep track of clients.
var currentClientNum = 0;
io.on('connection', (socket) => {
socket.clientNum = currentClientNum;
currentClientNum++;
onClientConnect(socket);
socket.emit('playerId', socket.clientNum);
...- Add a short handler to update your player number.
socket.on('playerId', id => {
me.id = id;
});- And finally, remove penguins when someone disconnects.
/// client side
socket.on('fwd:disconnect', playerId => {
console.log(playerId);
var toRemove = penguins.find(p => p.player === playerId);
if (toRemove) {
document.body.removeChild(toRemove.sprite);
}
penguins = penguins.filter(p => p.player !== playerId);
});- And on the serverside too.
/// server side, update onDisconnect to look like this.
socket.on('disconnect', () => {
onClientDisconnect(socket);
for (var i = 0; i < clients.length; i++){
clients[i].conn.emit('fwd:disconnect', socket.clientNum);
}
});Add that secret sauce of debugging, and voilà! A basic club penguin rip off.
The complete project can be found on Github at: https://github.com/hacksu/socket-penguin-club/tree/completed
Create a speech bubble and show a message for a penguin. Maybe even with browser notifications?