Home > Web Front-end > JS Tutorial > body text

Nodejs implements small game sharing for multiple people to move the mouse online at the same time_node.js

WBOY
Release: 2016-05-16 16:28:38
Original
1648 people have browsed it

Recently, due to project needs, I studied the websocket implementation of nodejs, socket.io, which is a widely used framework for websocket in nodejs background applications.

Preparation

1. Install socket.io, use the command npm install socket.io
2. For windows system, a vc compilation environment is required, because when installing socket.io, the vc code will be compiled

Basic principles of the game

1. The server monitors the client’s connection
2. When the client connection is successful, bind the page to move the mouse event, and process the event to send the current coordinates 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 disconnects, the server deletes its coordinate information and broadcasts it to other clients

Start implementing the 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:

Copy code 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

Copy code The code is as follows:

var positions = {};

Start monitoring the client’s connection and add a broadcast function (in fact, you can use the broadcast method io.sockets.broadcast.emit that comes with socket.io). The core code is as follows:

Copy code The code 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 ('posity.change', msg);
                }
            }
}
};
console.log(' // After the client connects successfully, the coordinate information of other clients will be sent
Client.emit('position.change', positions);
// Receive messages sent by the client
Client.on('position.change', function(msg){
                                        // Currently the client’s messages are only coordinate messages
        positions[client.id] = msg;
               // Broadcast the message to all other clients
broadcast({
            type: 'position',
Postion: 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 posts[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 posts[client.id];
               // Broadcast the message to all other clients
broadcast({
            type: 'disconnect',
              id: client.id
          }, client);
})
// Define client exception handling
Client.on('error', function(err){
console.log('error->', err);
})
});

Analyzing the above code, the key point is

1. The new client connects successfully and sends the coordinate information of other clients

2. When the client updates the coordinate information, it notifies 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 reference socket.io.js. This js can be found in the socket.io module. The path is generally node_modulessocket.ionode_modulessocket.io-clientdist, which contains merge and Compress the two versions, and you can use the merged version during development.

The complete code is as follows:


Copy code The code is as follows:




socket.io Multiple people interacting online at the same time Example






The img/cursor.png in the page can be found here, cursor.png. There are also many other mouse icons here. The principle of the front end is relatively simple. A simple analysis is as follows

1. When the connection is successful, bind the page mousemove event, which handles sending new coordinate messages
2. When receiving a message, according to the message type, the processing is to modify other client messages or remove other client messages
3. Define adding other client cursor icons and removing cursor icons
4. Handle client exception messages and add disconnection to allow the server to remove 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 to see the effect

Summary

The writing is more casual and refers to the amazing nodejs. This is a good book. Friends who want to understand nodejs can read this book.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template