Recently, due to the project needs, I have studied the websocket implementation of nodejs, socket.io, which is a framework widely used by nodejs background application websocket.
Preparation
1. Install socket.io and use the command npm install socket.io
2. For Windows systems, a vc compilation environment is required, because when socket.io is installed, the vc code will be compiled.
Basic principles of the game
1. The server listens to the client's connection
2. When the client connection is successful, the binding page moves the mouse event, and the current coordinate is sent to the server.
3. The server saves a global coordinate object and uses the client's unique number as the key value.
4. When a new connection comes, broadcast the coordinates to other clients
5. When the client is disconnected, the server deletes its coordinate information and broadcasts it to other clients.
Start implementing server code
When scoket.io establishes server monitoring, it needs to rely on an http connection to handle the upgrade protocol, so it also needs an http module, the code is as follows:
The code copy is as follows:
var http = require('http'),
io = require('socket.io');
var app = http.createServer().listen(9091);
var ws = io.listen(app);
Then define a global coordinate object
The code copy is as follows:
var posts = {};
Start listening to the client's connection and add a new broadcast function (in fact, you can use the broadcast method io.sockets.broadcast.emit, which comes with socket.io), and the core code is as follows:
The code copy is as follows:
ws.on('connection', function(client){
// Broadcast function
var broadcast = function(msg, cl){
for(var k in ws.sockets.sockets){
if(ws.sockets.sockets.hasOwnProperty(k)){
if(ws.sockets.sockets[k] && ws.sockets.sockets[k].id != cl.id){
ws.sockets.sockets[k].emit('position.change', msg);
}
}
}
};
console.log('/033[92m has a new connection:/033[39m', posts);
// After the client connection is successful, the coordinate information of other clients will be sent
client.emit('position.change', posts);
// Receive the client sends a message
client.on('position.change', function(msg){
// Currently, the client's message is only coordinate message
postions[client.id] = msg;
// Broadcast messages to all other clients
broadcast({
type: 'position',
post: msg,
id: client.id
}, client);
});
// Receive client closing connection message
client.on('close', function(){
console.log('close!');
// Delete the client and notify other clients
delete postions[client.id];
// Broadcast messages to all other clients
broadcast({
type: 'disconnect',
id: client.id
}, client);
});
// Disconnect
client.on('disconnect', function(){
console.log('disconnect!');
// Delete the client and notify other clients
delete postions[client.id];
// Broadcast messages to all other clients
broadcast({
type: 'disconnect',
id: client.id
}, client);
})
// Define client exception handling
client.on('error', function(err){
console.log('error->', err);
})
});
The key point of analyzing the above code is
1. The new client is connected successfully, and the coordinate information of other clients is sent.
2. When the client updates the coordinate information, notify other clients.
3. The client disconnects and notifies other clients
4. Broadcast message types are divided into modifying coordinates and removing coordinates
Write client html page
Since socket.io is a custom framework, the client needs to refer to socket.io.js. This js can be found from the socket.io module. The path is generally node_modules/socket.io/node_modules/socket.io-client/dist. There are two versions of merge and compression. You can use the merge version during development.
The complete code is as follows:
The code copy is as follows:
<!DOCTYPE html>
<html>
<head>
<title>socket.io Example of multiple people's simultaneous online interaction</title>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript" src="socket.io.js"></script>
<script type="text/javascript">
var ws = io.connect('http://localhost:9091/');
var isfirst;
ws.on('connect', function(){
console.log(ws);
// Start binding mousemove event
document.onmousemove = function(ev){
if(ws.socket.transport.isOpen){
ws.emit('position.change', { x: ev.clientX, y: ev.clientY });
}
}
})
ws.on('position.change', function(data){
// Start online at the same time
if(!isfirst){
isfirst = true;
// The first message is to receive coordinates of all other clients
for(var i in data){
move(i, data[i]);
}
}else{
// Otherwise, it is either a message that is disconnected or a message that is updated.
if('position' == data.type){
move(data.id, data.post);
}else{
remove(data.id);
}
}
})
ws.on('error', function(){
console.log('error:', ws);
ws.disconnect();
})
function move(id, pos){
var ele = document.querySelector('#cursor_' + id);
if(!ele){
// If it does not exist, it will be created
ele = document.createElement('img');
ele.id = 'cursor_' + id;
ele.src = 'img/cursor.png';
ele.style.position = 'absolute';
document.body.appendChild(ele);
}
ele.style.left = pos.x + 'px';
ele.style.top = pos.y + 'px';
}
function remove(id){
var ele = document.querySelector('#cursor_' + id);
ele.parentNode.removeChild(ele);
}
</script>
</body>
</html>
The img/cursor.png on the page can be found here, cursor.png, and there are many other mouse icons here. The principle of the front end is relatively simple. The simple analysis is as follows
1. When the connection is successful, bind the mousemove event on the page, and send a new coordinate message.
2. Received the message according to the message type, is it necessary to modify other client messages or remove other client messages?
3. Define adding other client cursor icons and removing cursor icons
4. Process client exception messages and add disconnection to allow the server to remove coordinate information
Running example
1. Save the server code as io_multigame.js
2. Save the client code as io_multigame.html
3. Run server code node io_multigame.js
4. Open multiple io_multigame.html pages to see the effect
Summarize
The writing is quite casual and references to the amazing nodejs. This is a good book. Friends who want to know nodejs can read this book.