Node. js allows you to share games where multiple users move their mouse online at the same time. node. JS is online at the same time.

Source: Internet
Author: User

Node. js allows you to share games where multiple users move their mouse online at the same time. node. JS is online at the same time.

Recently, due to project requirements, I have studied nodejs's websocket implementation, socket. io, which is a widely used framework of nodejs backend websocket.

Preparations

1. install socket. io and run the npm install socket. io command.
2. For windows systems, the vc compiling environment is required, because the vc code will be compiled during socket. io installation.

Basic game principles

1. The server listens to the Client Connection
2. When the client connection is successful, bind the page to move the mouse event, and process the event and send the current coordinates to the server.
3. The server saves a global coordinate object and uses the unique client number as the key value.
4. When new connections are available, broadcast 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

Scoket. io depends on an http connection for server listening. Therefore, an http module is also required. The Code is as follows:
Copy codeThe 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 codeThe Code is as follows:
Var postions = {};

Listen to the connection of the client and add a broadcast function (in fact, the broadcast method io. sockets. broadcast. emit can be used with socket. io). The core code is as follows:

Copy codeThe 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 ('position. change', msg );
}
}
}
};
Console. log ('\ 033 [92m has a new connection: \ 033 [39m', postions );
// After the client connection is successful, the coordinates of other clients are sent.
Client. emit ('position. change', postions );
// Receive messages sent from the client
Client. on ('position. change', function (msg ){
// Currently, only coordinate messages are sent to the client.
Postions [client. id] = msg;
// Broadcast messages to all other clients
Broadcast ({
Type: 'position ',
Postion: msg,
Id: client. id
}, Client );
});
// Receives the connection message from the client.
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 to analyzing the above Code is

1. The new client is successfully connected and the coordinates of other clients are sent.
2. When the client updates the coordinate information, it notifies other clients
3. Disconnect the client and notify other clients
4. The types of broadcast messages include modifying coordinates and removing coordinates.

Compile the client html page

Because of socket. io is a custom framework, so the client must reference socket. io. js. This js can be used from socket. in the io module, the path is generally node_modules \ socket. io \ node_modules \ socket. io-client \ dist, which has two versions of merging and compression. You can use the merged version during development.

The complete code is as follows:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Title> socket. io multi-user online interaction 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 ){
// Start other clients that are online at the same time
If (! Isfirst ){
Isfirst = true;
// The first message is the coordinates of all other clients.
For (var I in data ){
Move (I, data [I]);
}
} Else {
// Otherwise, there will be another disconnected message or another 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>

The img/cursor.pngon the page can be found here, cursor.png, there are many other Mouse icons here, the front-end principle is relatively simple, simple analysis is as follows

1. When the connection is successful, bind the page mousemove event to process the new coordinate message.
2. The message received is based on the message type, whether to modify or remove messages from other clients.
3. Define adding other client cursor icons and removing cursor icons
4. Handle client exception messages and add disconnect to remove coordinate information from the server

Running 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

This is a good book. If you want to know about nodejs, you can read this book.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.