Nodejs realizes the small game sharing that many people move the mouse online at the same time
- 2020-03-30 04:32:13
- OfStack
Recently, due to the need of the project, we studied nodejs websocket implementation,socket.io, which is nodejs background application websocket widely used framework.
The preparatory work
1. Install socket. IO using the command NPM install socket. IO
2. Vc compiler environment is required for Windows system, because vc code will be compiled when socket.io is installed
Game fundamentals
1. The server listens for client connections
2. When the client connects successfully, the binding page moves the mouse event, and the current coordinate is sent to the server
3. The server holds a global coordinate object and takes the unique number of the client as the key value
4. When a new connection comes in, broadcast the coordinates to another client
5. When the client disconnects, the server deletes its coordinate information and broadcasts it to other clients
Start implementing server-side code
Ket. IO when setting up server monitor, 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:
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
var postions = {};
To start listening to the client's connection, and the function of the new radio (actually available socket. IO's own broadcasting method IO. Sockets. The broadcast, emit), the core code is as follows:
ws.on('connection', function(client){
//The 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 There's a new connection :033[39m', postions);
//After a successful client connection, the coordinate information of the other client is sent
client.emit('position.change', postions);
//The receiving client sends a message
client.on('position.change', function(msg){
//The only message on the client side is the coordinate message
postions[client.id] = msg;
//Broadcast the message to all other clients
broadcast({
type: 'position',
postion: msg,
id: client.id
}, client);
});
//Receive client close connection message
client.on('close', function(){
console.log('close!');
//Delete the client and notify other clients
delete postions[client.id];
//Broadcast the message 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 the message to all other clients
broadcast({
type: 'disconnect',
id: client.id
}, client);
})
//Define client-side exception handling
client.on('error', function(err){
console.log('error->', err);
})
});
The key to analyzing the above code is this
1. The new client connects successfully and sends coordinate information of other clients
2. Notify other clients when the client updates coordinate information
3. Client disconnects and notifies other clients
4. The broadcast message types are divided into modified coordinates and removed coordinates
Write client-side HTML pages
As socket.io is a custom framework, so the client side needs to reference socket.io.js, this js can be found from 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, development can be used to merge version.
The complete code is as follows:
<!DOCTYPE html>
<html>
<head>
<title>socket.io Multiple people interact online at the same time example </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 the 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){
//
to start other clients online at the same time
if(!isfirst){
isfirst = true;
//The first message is to receive the coordinates
of all other clients
for(var i in data){
move(i, data[i]);
}
}else{
//Otherwise, it's either a disconnected message or a message that updates the coordinates
if('position' == data.type){
move(data.id, data.postion);
}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, create
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>
Img /cursor.png in the page, can be found here,cursor.png, there are also a lot of other mouse ICONS, the principle of the front end is relatively simple, simple analysis as follows
1. When the connection is successful, bind the page mousemove event, which will handle sending the new coordinate message
2. Received message according to the message type, whether to modify other client messages or remove other client messages is processed
3. Define adding other client cursor ICONS and removing cursor ICONS
4. Handle the client exception message and add a disconnect to make the server remove the coordinate information
Run the example
1. Save the server code as io_multigame.js
2. Save the client code as io_multigame.html
3. Run the server code node io_multigame.js
4. Open multiple io_multigame.html pages, you can see the effect
conclusion
It is written loosely, with reference to the great nodejs, which is a great book for those of you who want to know more about nodejs.