Github blog: github.com/aototo/blog like friends star support
I haven’t written much articles for two months. This project made an HTML5 online real-time game, which was written based on socket. IO architecture. There are also a lot of online materials, which are scattered and wordy. Here is a summary of the whole process, broaden the ideas. (PS: Mainly the idea of the whole process, not the basic usage of the framework)
-
Create a Node server
var app = require('http').createServer(handler) var io = require('socket.io')(app); var fs = require('fs'); app.listen(8080.function() { console.log('Listening at localhost:8080')});var room = {}; // Handle the event after the client connects io.on('connection'.function(client) {... });Copy the code
-
Create a game room
// Client: randomly generate a room keyId and send it to the back end var socket = io.connect(); socket.emit('create', roomId); // Server: io.sockets.on('connection'.function(client) { // Accept the CREATE event and join the roomId client.on('create'.function(roomId) { // You can record the roomId here and save it to the Rooms array // rooms.push(roomId) client.join(roomId); }); });Copy the code
-
Generate room links, or QR codes
You can use QrcodeJS to generate qr codes. This is done by generating a Url with code. The player determines if there is a room based on the Code. If yes, join; if no, create.
To generate the Url
new QRCode(document.getElementById("qrcode"), location.href + 'play.html? id=' + ID);Copy the code
-
Player joins the room
By scanning the TWO-DIMENSIONAL code, the roomId in location.search is obtained, and then sent to the back end to join the room
var roomId = location.search.replace('? id='.' '); // client: get room id socket.emit('join', { roomId: roomId, ... }); // Server IO.sockets. On ('connection'.function(client) { ... client.on('join'.function(data) { client.join(data.roomId); // Notify other players in room IO. In (data.roomid).emit('new_player', data); }); . }Copy the code
The server receives the join event, and when the client joins the room, it notifies other players in the room.
-
Get the room ID requested by the player by getting client request
//node.js var url = client.request.headers.refererCopy the code
Every time a player sends a request, there is no need to carry the room ID each time.
-
Create player data
Each player generates a fixed user Id, which is stored in the server and localStorage on the client
user = { id: null, rooms: [ { roomId: null, data: null} ] }Copy the code
Each player who connects to the backend can create a data set that can be used to recover the lost data.
The general process is above, the specific use of socket can refer to the official website demo, here is just a general process ideas. Emit (client) -> on(server) – emit -> on(client), very simple.