Home  >  Article  >  Web Front-end  >  JavaScript implements automatic reconnection of HTML5 games after disconnection

JavaScript implements automatic reconnection of HTML5 games after disconnection

小云云
小云云Original
2018-02-09 13:51:031729browse

Requirements for disconnection and reconnection 1. Principle of disconnection and reconnection 2. Automatic reconnection within the game without refreshing 3. Refreshing the game automatically reconnecting and reconnecting data Locationreplace reset url reconnecting 4. The final summary of the reconnection mechanism in actual projects The need for line reconnection, especially on mobile phones, may cause the user's socket link to be disconnected due to network instability or other reasons. At this time, if the player is directly asked to exit the game and log in again, it will undoubtedly greatly affect the user experience. Therefore, based on this demand, there is a need for programs to realize the technology of automatically reconnecting after disconnection, so that users can quickly start the game and fight again.

1. Principle of disconnection and reconnection

It turns out to be very simple, that is, when the connection is disconnected, according to the user’s click (some time is short, there is no need to click, the default is to automatically reconnect back ), the program automatically identifies whether to refresh and re-enter the game or to help the user automatically reconnect. The client will automatically do things for the user based on the automatic reconnection mark. For example, automatically log in, select a character, enter a scene, request synchronization of background data, etc.

According to the implementation mechanism, it can be roughly divided into two implementation methods. The main ones are automatic reconnection in the game (without refreshing) and automatic reconnection after refreshing the game. The two implementation mechanisms will be discussed in detail later, as well as the related pros and cons.

2. Automatic reconnection in the game (without refreshing)

This is more difficult, because if the game is not refreshed, the client data will be disconnected for a period of time. Server data is out of sync. For example, the location of monsters, rewards obtained, progress, etc. These need to be designed from the beginning. If the planner requires adding this at a later stage, it will be almost impossible to achieve because the changes will be too big. So assuming that there are so many, it is probably similar to the following method. (If you really want details, I will write a new blog:)

1. The client and the server have agreed on which data needs to be synchronized by the client

2. How long does it take to disconnect? Automatic reconnection (planning and technical implementation to evaluate each other)

3. The server provides an automatic reconnection protocol, and at the same time, the relevant data should not be destroyed as soon as the user disconnects (this is more complicated, For example, whether the automatic battle should always be hung on the server, and some other related operations)

4. The client does not refresh the game, uses the new interface to reconnect to the server, and automatically updates and synchronizes the corresponding data (such as synchronizing monsters position or other character positions, etc.)

This technology is generally used in turn-based games and does not generally involve a combat system. If arpg is used, it can only automatically reconnect within a short period of time, otherwise the variables will be too great. Or some variations need to be made, such as refreshing monsters in simple scenes, but special processing such as reloading scenes such as world bosses.

3. Refresh the game and automatically reconnect

I personally feel that this is a simple, crude and practical method. Most games are suitable for use. As long as you refresh, the game data will be lost and everything will start again. The client only needs to do some automated operations based on the marks, which is much easier. , and at the same time, the server does not need to be changed, and it is stable and error-prone. The only bad thing is that the user experience will be slightly worse.

Reconnection data

String data:

//ip + 用户标识 + 服id + 服名字 (数据根据自己项目情况)
var reload:string = ip + "#" + token + "#" + serverId + "#" +serverName;
//后面的reload字符串都是这里的内容

Reconnection identification:

reload //String

Note: Refresh You can only refresh your own page. (For example, when inside an iframe)

Location.replace reset url and reconnect

This is relatively simple and there will be no compatibility issues. That is, when reconnecting, record the previous logged-in user and server address

Add parameters through the url, and finally parse them out during actual use, and determine whether the attributes are overloaded.

The replace() method of the Location object: replaces the current document with a new document.

By passing in a new url (actually the original url + attached reconnection data)

location.replace(oldUrl + "reload#" + reload);

must use the url, and it also needs to be compatible with the original parameters. In the game, the URL may be like this:

地 debug 1

http://localhost:63342/game/index.html?reload=1&host=ws://192.168. 0.10:1050/ws&token

A cookie is a variable that is stored on the visitor's computer. This cookie is sent each time the same computer requests a page through a browser. You can use JavaScript to create and retrieve cookie values.

It is also more convenient to use the local storage function of cookies, but some mobile browsers may not be able to read it.

document.cookie = "reload#" + reload;

1. Use Html5’s window.localStorage

localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The difference is that the data stored in localStorage has no expiration time, while the data stored in sessionStorage will be cleared at the end of the browser session (browsing session), that is, when the browser is closed.

It should be noted that the data saved in either localStorage or sessionStorage is limited to the protocol of the page.

Since it is an H5 game, of course the focus is on using this. Let’s take a look at the localStorage API
first.

window.localStorage.setItem("reload", reload);

Read:

var reload = window.localStorage.getItem("reload");

1. Use Egret’s local storage

It will be more convenient to use Egret. It is encapsulated and can be supported by H5 and packaged locally. localStorage.ts

egret.localStorage接口
//保存数据
export let getItem:(key:string)=>string;
//删除数据
export let removeItem:(key:string)=>void;
//将所有数据清空
export let clear:()=>void;
Web实现类WebLocalStorage.ts
namespace egret.localStorage.web {
function getItem(key:string):string {
return window.localStorage.getItem(key);
}
function setItem(key:string, value:string):boolean {
try{
window.localStorage.setItem(key, value);
return true;
}
catch(e){
egret.$warn(1047, key, value);
return false;
}
}
function removeItem(key:string):void {
window.localStorage.removeItem(key);
}
function clear():void {
window.localStorage.clear();
}
localStorage.getItem = getItem;
localStorage.setItem = setItem;
localStorage.removeItem = removeItem;
localStorage.clear = clear;
}

可以看到内部其实也是采用了window.localStorage来进行实现,同时做了一场处理,最后是通过localStorage接口进行赋值给外部调用。下面是实际使用方法:

//使用egret的本地存放方法做
egret.localStorage.setItem("reload",reload);
//游戏中获取
var reload:string = egret.localStorage.getItem("reload");

四、实际项目中处理重连机制

这里的代码是刷新之后重新进入游戏,然后通过之前的数据(url或者本地缓存)解析出相应的数据来进行判断。

解析url

var reload:string = location.href;

本地缓存获取数据

var reload:string = egret.localStorage.getItem("reload");
console.info("reload数据:" + reload);
if(reload && reload != "")
{
var cooks:string[] = reload.split("#");
console.info("断线重连刷新过来的");
this.session.isReload = true;
this.session.host = cooks[0];
this.session.token = cooks[1];
this.session.serverId = Number(cooks[2]);
this.session.serverName = cooks[3];
}

通过游戏内的变量进行判断处理

if(this.session.isReload)
{
//开始自动重连,走额外的协议以及自动处理
}
else
{
//走正常的流程
}

最后的总结

断线重连这里主要是讲了一些思路以及实际项目中的应用。代码算是伪5代码了,读者应该根据自己项目实际情况来设计,做一些相应变化,原理是一样的。

我们有一个项目是有遇到过其中的一个问题,因为一开始没有考虑自动重连的问题,在客户端和服务器都没这里的考虑。所以没办法做到不刷新游戏来进行重连(主要是成本太大,又是arpg游戏),最终是选择了游戏自己刷新来实现的机制的。当然也会遇到一些坑,比如接入一些平台,只能刷新自己的html,无法刷新平台的html(游戏内嵌),导致平台的sdk的问题(影响充值、关注等等)。不过最终都是有通过变通之类的进行解决了。

相关推荐:

PHP连接MySql闪断自动重连的方法_MySQL

The above is the detailed content of JavaScript implements automatic reconnection of HTML5 games after disconnection. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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