# 【转载】基于多层结构的网络游戏平台的研究与应用

53 篇文章 2 订阅

## 基于多层结构的网络游戏平台的研究与应用



1.1 网络游戏平台的发展背景	8
1.2 国内外现状	9
1.3 本文的研究内容	9

2.1 网络游戏的概念	10
2.2 网络游戏的类型	10
2.3 国内网络游戏的发展历程	12
2.4 网络游戏的特征	13

3.1 C/S模式	14
3.1.1 C/S工作原理	14
3.1.2 TCP工作机制	14
3.2 B/S模式	16
3.2.1 B/S工作原理	16
3.2.2 HTTP工作机制	17
3.3 C/S模式与B/S模式的比较	18
3.4 三层及多层软件体系结构	18
3.4.1 二层结构的退出	18
3.4.2 三层及多层结构原理	19
3.4.3 三层及多层结构的特点	21

4.1 基于集群技术的四层平台体系结构	22
4.1.1 集群的提出	22
4.1.2 集群技术的概念及特点	22
4.1.3 平台体系结构	23
4.2 游戏通信平台GateServer	25
4.2.1 通信平台GateServer的设计框架与特点	26
4.2.2 通信平台GateServer网络底层	28
4.2.3 通信平台GateServer网络中层	30
4.2.4 网络通信平台GateServer的接口设计	31
4.3 统一格式的通信数据包	32
4.3.1 通信包的设计	32
4.3.2 通信包的通信控制	34
4.4 多线程实现	36

5.1 平台设计目标	38
5.2 平台架构设计	39
5.2.1 平台开发运行环境	39
5.2.2 四层C/S体系架构	41
5.3 平台网络结构	43
5.4 平台数据库设计	43
5.5 平台功能模块设计	45
5.5.1 系统服务模块	45
5.5.2 受控安全模块	46
5.5.3 启动平台模块	47
5.6 平台的容灾机制	48
5.7 平台的安全性设计	49
5.8 平台的特点与可扩展性	50

6.1 总体框架	52
6.2 网络层实现	52
6.3 命令处理层实现	53
6.4 虚拟世界层实现	54

“负载均衡”已经不能算是什么新鲜话题了，从硬件到软件，也都有了很多的方法来实现负

1. 学习研究了网络游戏的相关知识。对网络游戏的概念、发展历程、分类、特征等进

2. 深入研究并分析了应用平台的体系结构。对当前已广泛应用的C/S模式、B/S模式和

3. 自主设计了网络游戏平台的基本架构，要点如下：
⑴根据游戏用户数量需求、网络技术现状和负载均衡等基本要求，采用了集群技术。集

⑵我们采用了服务器集群技术，并将平台设计为四层的C/S结构，第一层是客户端，提

⑶数据服务器采用备份功能和建立专门的灾备中心，保证平台系统可靠运行。
(4)从网络环境、法律上人为规定制度、数据安全与系统可靠性、权限管理、系统监控

4. 网络游戏平台中实现了下列关键技术
⑴游戏通信平台GataServer。GateServer作为网络游戏数据交互的接口，是游戏客户端

⑵通信数据包。它是服务器和客户端的游戏协议部分，即游戏服务器和客户端的通信规

⑶多线程。在网络游戏设计中，由于大量的用户参与游戏，所以在服务器端必须使用多

5. 详细阐述了游戏服务器的实现过程，讨论了游戏器服务器的总体框架，包括网络层、

The research and application based on multilayer constructed network game platform

Summary
Chinese network game estate is at present prompt developing, in 2004 Chinese network game
marketable value amounts to RMB 2,470,000,000, grows by 47.9%, it is estimated that Chinese
network game publishes the marketplace income from sales of products in 2009 will reach RMB
10,960,000,000. In our country the network game players already approached 20 million. So
ample and be rapidly growing players with a team, is the development of enormous network game
potential and basis without doubt. Our country network game enormous market has potential, high
earn profit, height grow up limpid profit of the pattern clearly, makes network game become one
of the most estate that Internet is found satisfactory most in industry, such a piece of enormous
cake seducing others to prospect, will attract fierce striving beyond doubt, also will make network
game industry get unparalleled development at the same time.
Although the game profession development is rapid, but from the whole looked the influence
network game operation success or failure has two key aspects: Is plays itself may play the natural
and the later period operation; Another is comes up the guarantee overall system from the
overhead construction to be stable, the highly effective movement. At the same time, along with
the game user scale rapid growth, the Internet scale suddenly expands, the band width unceasingly
increases, the demand trend diversification, the server withstands the pressure is more and more
big along with it. In this kind of situation, urgent needs to have the fast response ability, high
expandable, Gao Ke with the information server which, is easy to manage, can at any time
high-grade measures land processes the large-scale user the concurrent service request. The colony
system has the very high overall performance (for example when response asked, turnover rate),
the high expandability, the high usability, the higher performance/price compared to, is at present
domestic and foreign constructs the high performance, the complex distributional application main
development direction. Uses the colony technology has become a leading tendency as the strut
network game platform.
Now, the fast ethernet, kilo mega backbones Ethernet foundation and the high performance,
high redundant reliable server already became the network game network operation the core, three
were gradually mature with the multilayered software system structure as well as the colony
technology, causes the network game platform the research and the development completely
becomes possibly, and could satisfy at the same time several hundred thousand users on-line.
Among them, the colony technology is along with the computer in social life each level widely a
software domain which using the recent years rapid development, expanded, was the large-scale
system solution load equalization question essential technology.
Customer/server model with three layers and multilayer construction are one kind of
advanced coordination application procedure development models. Along with the network
communication and the computer technology unceasing development, enterprise's information
system and formerly compared, had the huge progress. The enterprise level application no longer
satisfies the simple customer/server system, but is unceasingly is making great strides forward to
the three layered or multilayered system structure distributed environment. Compare to the two
layer structures application software under the traditional C/S pattern, the multilayer construction
application software has the good expandability, the strong manageability, the high security,
software entrusts with heavy responsibility the nature to be good as well as to save the
development time and so on many merits. Under the Internet/Intranet environment, these merits
appear prominently. In three or the multilayered design model, distributes the database visit in or
many intermediate levels. The customer procedure and the database connection by the
intermediate level shield, the customer procedure only can indirectly visit through the intermediate
level the database. The intermediate level possibly moves in is different on the client other
machines, after passes through the reasonable duty division and the physical deployment, may
cause the overall system the operating duty to hasten equilibrium, thus enhances the overall
system the operating efficiency.
The colony technology has solved the large-scale system load equalization problem, it can
satisfy the large-scale system service, the performance as well as the scale well and so on the daily
aggregate demand. Along with the computer network development and the large-scale science
computation like gene data analysis, the weather forecast, the petroleum prospecting are more and
more high to the server performance requirement, set a higher request to the computer
performance: Needs the hardware to have the nimble extendibility, the crucial service needs the
reliable fault-tolerant mechanism. But the working pattern already had, appears actually to the
new demand lacks the ability to do what one would like. Therefore, how guaranteed a large-scale
system has the processing speed quickly, the I/O volume of goods handled is big, the fault
tolerance good, the reliability is high, moreover also has good may expand ability, becomes the
current urgent need solution the topic. Meanwhile in the network application, the loads balance
already could not be any new topic, from hardware to software, also all had very many methods to
realize the loads balance. The loads balance that we discuss here, is not refers depends upon DNS
to change the loads balance which or other hardware equipment and so on does, but refers to the
loads balance which does in the application layer. In this demand environment, the cluster system
emerged. Compares with the traditional high performance computer technology, the colony
technology may use various scales the computer to take the node, not only the system construction
cost is low, but also may realize the very high operating speed, completes the big operand the
computation, can gradually meet the information service need which day by day grows now. In
Cluster Server System, the server is no longer distributed in various places, but together for
unified management and maintenance. Distributed systems maintain a client / server model of
development, the advantages of scalability, also have a terminal / server model of resource sharing
and the advantages of centralized management easier. In next face in Internet service application,
takes the support by the high performance hardware platform, the parallel technical application in
the server domain, is the inevitable trend which the computer develops.The parallel processing
technology in the high performance computation domain, high available and the high performance
is the colony server system development two important directions.
In view of the above discussion, the author proposed take the colony technology as the
foundation frame multi-layered software architecture network game platform, this system design
development goal is must establish one stable, the reliable network game platform attracts and
maintains generally swims plays the family.
The article has carried on the outline to the software architecture, the key discussion
multi-layer software architecture technology, simultaneously studied has analyzed the colony
technology. Unite the reality, the use sandwich construction, the colony technology have carried
on the concrete application in the network game platform. This article research content includes:
First chapter mainly introduced the topic development background, the research goal and the
significance, the domestic and foreign research condition as well as this article main research
content. Second chapter introduced the network game concept, the type, the domestic
development course and its the characteristic, enable us to have a quite clear understanding to the
network game. Third chapter mainly elaborated at present system structure which uses using the
platform, including the C/S pattern principle of work and the corresponding TCP work mechanism,
the B/S pattern principle of work and the corresponding HTTP work mechanism, and has carried
on the comparison to C/S and the B/S these two kind of patterns. Finally introduced already
widely applied in the system three and the multilayered software system structure. Fourth chapter
introduced the network game platform system structure and its the essential technology. First
introduced based on the colony technology four platforms structure, puts forward, the concept and
the characteristic and the platform structure detailed description including the colony. Then
introduced the related essential technology, including game communications platform GateServer
design and realization, correspondence data packet design and multi-thread realization. Fifth
chapter introduced the platform system design. Including the design goal, is soft, the hardware
platform choice, the system overhead construction design, the system network deployment
structure, the database design, the platform function module (including system service module, is
controlled security module and starts platform module) the design, the platform accommodates the
disaster mechanism, the secure design, the characteristic and may extended and so on. Sixth
chapter detailed elaboration game server realization process. First introduced the game server
overall frame, including the network level, the demand processing level and the hypothesized
world level three parts, then separately has carried on the detailed description to their realization.
The seventh chapter summary research work and the full text, and proposed some improvements
places and the future work direction.
The article studies the essential technology, innovation and do the work is as follows:
1. The study of the network game related knowledge. To the network game concept, the
development course, the classification, the characteristic and so on have conducted the detailed
research and the elaboration.
2. Thoroughly studied and analyzes has applied the platform the system structure. To
presently already the widespread application C/S pattern, the B/S pattern and the sandwich
construction principle and the characteristic have done the research and the analysis.
3. Act on self's own having designed fundamental network game platform frame, essential as
follows:
(1) According to plays the user quantity demand, the network technology present situation
and the load equalization and so on the basic request, has used the colony technology. In the
colony system may dynamic join the server which the new server and the deletion needs to
eliminate, has very strongly may the extension, thus can maximum limit expand the application
need which the system satisfies unceasingly grows;moreover, the colony system has the usability,
namely can provide the uninterrupted service for the user, when in a system point appears the
breakdown time, the overall system still could continue for the user to provide the service; At the
same time, because players distribute in different areas, we lay aside a complete game world
server cluster system in the different region, like this causes to play the family to be allowed to
visit leaves their recent server cluster system, to players experiences the quicker speed of response,
to the service provider said saves the network band width, reduces the cost.
(2) We have used the server cluster technology, and the platform design is four C/S structure,
first is the customer end, provides the user the connection. The second layer is the
communications game platform (gateway server), this is server cluster's only entrance, retransmits
all functions request for the service point pond in concrete server, and processing all non-
functions requested, and manages the terminal user, carries on the condition to maintain, the diary
record and so on. The third layer provides the actual service the server group, processing and only
processes all functions request, does not participate in the user management, the condition
maintenance and so on, provides the purest function service. The fourth layer is the database
memory system, which is responsible for manages of the logarithm according to read-write and
maintenance, stably provides, the consistent data access service for the entire colony interior
movement.
(3)The data server uses the backup function and the establishment special disaster prepares
the center, guarantees the platform system reliable movement.
(4) From the network environment, the law the artificial stipulation system, the data security
and the system reliability, the jurisdiction management, the system monitoring and so on many
aspects design guarantee the entire platform system the security and the reliability.
4. In the network game platform has realized the following essential technology.
(1) Game communications platform.GateServer took the network game data interactive
connection, is plays the customer end to turn on the server, the realization customer end to game
server between data interactive. Uses the Winsocket network programming realization to play the
family and the game server correspondence, simultaneously fully was considering "the
performance" and "might the extension" in two proper attentions to both situations, we play
communications platform GateServer to divide into the network first floor and the network
intermediate deck serves two structures. The special-purpose game communications platform is
advantageous to the realization reasonable load balance, forms simply, is consistent, the nimble
distributional processing correspondence environment.
(2) Communication data packet.It is the server and the customer end game agreement 's
partial, namely game server and customer end correspondence rule. The network game
correspondence data packet is the network package, has an accurate logical significance the data
packet is the logical package, we use the way is has many the accurate logical significance a
logical package of group to synthesize a network package, like this enhanced the transmission
efficiency, reduced network band width occupation ratio, reduced the transmission data packet
frequency.
(3) Multithread. Designs at the network game, because the massive users participate in the
game, therefore must use many lines regulation in the server end to carry on the network receive,
operation and so on transmission, processing data packet. But in order to be advantageous for to
many lines regulation carries on the maintenance, we encapsulate many thread into Thread Pool,
will use for to establish, conclusion, assignment labor 作线regulation duty and so on work.
5. In detail elaborated the game server realization process, discussed the game server overall
frame, including the network level, the demand processing level and the hypothesized world level
three parts, and separately has carried on the detailed description to their realization.
three section networks game obtained the actual utilization, in which "WOQII"  swims plays the
family at the same time the online population to achieve several ten thousand, has obtained the
very good economic efficiency.
"Journal of Computer Applications".
Keywords: Network game, System structure, Colony, multithread, Communication
platform, communication data packet

1.1 网络游戏平台的发展背景

1.2 国内外现状

1.3 本文的研究内容

TCP工作机制，B/S模式的工作原理及相应的HTTP工作机制，并对C/S 与B/S这两种模



## 第二章 网络游戏概述




## 6.1 总体框架

6.1 游戏服务器的层次

1、接收数据包队列及接收线程：用于存放刚收到的数据包，此数据包还没有进行逻辑意义上的拆解，接收线程从此队列中取出数据包，并将其形成一个逻辑意义上完整的数据包加入到“处理数据包队列”中；

2、处理数据包队列及逻辑处理线程：已经拆解成了逻辑意义上的数据包，逻辑处理线程对此类数据包进行逻辑解析，这里就是服务器的主要逻辑部分，有的数据包在处理完成后，可能是需要向网关服务器GateServer返回处理结果的，此时就需要逻辑线程在处理完成后将返回结果的数据包放入“发送数据包队列”中；

3、发送数据包队列及发送线程：待发送的数据包队列，由发送线程根据数据包里的套接字发送给GateServer，然后有GateServer转发给特定的客户端。

## 6.2 网络层实现

1） CConnectPoint：基类，创建、处理接收链表RecvBox

2） CNetClientCompletionPort(Socket接收发送的NetClient)

3） CConnection：用于数据的打包发送，联接的维持，包括：i.打包发送，逻辑数据通过PushToSend（）打包，只有在调用SendNow()的时候才会全部发送；ii.连接的维持，连接用心跳来维持，如果长时间没有心跳，则连接断开（不再接收发送）。

1） Init(const SOCKET&    socket, const sockaddr_in& addr, DWORD dwID, CConnectPoint * pCP, DWORD nAuthID)系统初始化

2） Destroy() 释放系统资源

3） Connected() 建立与通讯服务器GateServer的连接

4） DisConnected() 关闭与通讯服务器GateServer的连接

5） PushToSend( void * pBuf, int nSize, WORD type, WORD * para = NULL)把数据打包加入发送链表，等待发送

6） SendNow() 发送发送链表的数据

7） RecvToBuf() 接收数据,并加入到接收链表

8） IsConnected() 检查网络连接状态

## 6.3 命令处理层实现

classCServerMessageExplain

{

public:

staticCServerMessageExplain* m_pServerMessageExplain;

public:

CServerMessageExplain();

~CServerMessageExplain();

//解析指令函数

int Explain(char* pBuf, int nPackSize, CObject* pObject);

};

Explain函数的实现如下

intCServerMessageExplain::Explain(char* pBuf, int nPackSize, CObject* pObject )

{

if( ! pBuf || (nPackSize<=0) )

return -1;

if( !pObject )

return -1;

{

case FMI_CTOS_ER_USEUIITEM: //使用技能/物品/表情

{

…

}

break;

case FMI_CTOS_ER_ALLOT_ATTRIBPOINT: //交易系统：向服务器发送某个交易的动作

{

}

break;

case FMI_CTOS_ER_CHAT:    // 聊天系统：客户端向服务器发频道开关信息

{

}

break;

case FMI_CTOS_ER_SET_MAKE_FRIEND_STATUS: //设置玩家的状态(是否充许别人与他交友)

{

}

break;

……

default:

break;

}//end switch()

return 1;

}

## 6.4 虚拟世界层实现

6.2 虚拟世界层结构

1物体的统一创建与删除

2物体的定时器

3物体的查找

6.3 物体类结构图

// Object.h: interface for the CObject class.

#ifndef __COBJECT_H__

#define __COBJECT_H__

class CObject

{

public:

long GetObjectType();

void SetObjectType(long type);

void SetUniqueId(long id);

long GetUniqueId();

virtual void HeartBeat();

CObject();

virtual ~CObject();

private:

long m_uid;                            // 物体ID

long m_obType;           // 物体类型

};

#endif

// Object.cpp: implementation of the CObject class.

#include "Object.h"

CObject::CObject()

{

}

CObject::~CObject()

{

}

void CObject::HeartBeat()

{

}

// 取得物体的ID

long CObject::GetUniqueId()

{

return m_uid;

}

// 设置物体的ID

void CObject::SetUniqueId(long id)

{

m_uid = id;

}

// 设置物体的类型

void CObject::SetObjectType(long type)

{

m_obType = type;

}

// 取得物体的类型

long CObject::GetObjectType()

{

return m_obType;

}

6.4 物体对象模型

// 创建一个新物体

CObject *CMatrix::CreateObject(long type)

{

CObject *ob = NULL;

// 根据物体类型创建实例

switch(type)

{

case OTYPE_ITEM:

ob = new CItem;

break;

case OTYPE_HUMAN:

ob = new CHuman;

break;

}

if(ob)

{

// 设置ID

ob->SetUniqueId(m_seq++);

// 添加到物体列表中

m_obList.push_back(ob);

}

return ob;

}

// 销毁一个物体

void CMatrix::DestroyObject(CObject *ob)

{

// 从物体列表中清除

m_obList.remove(ob);

// 释放内存

delete ob;

}

// 根据ID查找物体

CObject * CMatrix::FindObject(long uid)

{

CObject *ob = NULL;

list<CObject*>::iterator it;

for(it = m_obList.begin(); it != m_obList.end();it++)

{

if((*it)->GetUniqueId() == uid)

{

ob = (*it);

break;

}

}

return ob;

}