网络在线游戏开发心得服务器端javaOnline game development experience server side Java.docx
- 文档编号:28773739
- 上传时间:2023-07-19
- 格式:DOCX
- 页数:8
- 大小:19.41KB
网络在线游戏开发心得服务器端javaOnline game development experience server side Java.docx
《网络在线游戏开发心得服务器端javaOnline game development experience server side Java.docx》由会员分享,可在线阅读,更多相关《网络在线游戏开发心得服务器端javaOnline game development experience server side Java.docx(8页珍藏版)》请在冰豆网上搜索。
网络在线游戏开发心得服务器端javaOnlinegamedevelopmentexperienceserversideJava
网络在线游戏开发心得(服务器端、java)(Onlinegamedevelopmentexperience(serverside,Java))
Onlinegamedevelopmentexperience(serverside,Java).Txt,Iwouldliketoknow,howmanypeopleseparated,orstilllove?
.Hislaughtocryyourselftowatchtheirowntrouble.Youusestealthtoavoidme,Iusestealthtohelpyou!
Untiloneday,inthehandsofpower,killalltheworld,bearmydog.Amultiplayeronlinechessgameprojectisdrawingtoaclose.Iparticipatedintheentiredesignflowoftheprojectandcompletedthecorecodeof90%.There'salottobetalkedaboutabouttheproject.Thisseriesisnotgoingtobeaverydetailedspecificationoftheproject,whichshouldbedescribedinthedesigndocument,andIintendtosayonlyafewpointsofnote.
Onespecialthingaboutthisprojectisthattheclientisamobilephoneandtheuseriscommunicatingwiththeserveroverthemobilenetwork.ComparedwithPC,theprocessingcapacityofmobilephoneisveryweak,andthenetworktrafficcostisexpensive.Becauseinadditiontoconsideringsomeofthegeneralonlinegameproblems,thesetwopointsalsoneedtobefullyconsideredinthedesign.
Firstofall,thechoiceoflanguagedevelopment,becausetheserverisLinuxenvironment,MStechnologydirectlyruledout,asforMONO,well,Ireallydonotworry.ThealternativeisC++andJava,Javawinsinthenetworkformidableability,thedevelopmentcycleisshort,hasmanyframeworksandtheopensourcestorehousesupport,writestherottenunacceptablecodeisnoteasy;C++winsinthespeed.Inallitsaspects,C++madeiteasiertoturnthisprojectintoabunchofcodenightmares,andwechoseJava.
I.network
Onlinegames,thefirstproblemfacing,ofcourse,ishowtonetworkcommunications.ThefirstthingtoconsideristheHTTPprotocol,becausealltheJ2MEphonessupportthis,andwecertainlywanttobeascompatibleaspossible.Moreover,theHTTPprotocolencapsulationisveryhigh,withoutconsideringthreads,synchronization,statusmanagement,connectionpooling,buttheHTTPprotocolhastwouncomfortableplaces:
Thisprotocol,thisproblemhasplaguedmanypeoplemanytimes.IhaveconsideredthesolutionistotransformtheHTTPprotocol,socketdoesnotcloseafterthedatatransferiscomplete,buttheworkloadisverylarge,theprojectcycle,basicallyistheMissionimpossible,willnotbeconsidered.Theclientcanonlyrequestdatafromtheserverbypolling.
Whenthenetworktrafficistoolarge.Onthisproject,justpassedbetweenthenetworkinstruction,buteachpasstoaddauselessHTTPHead,plustheclientneedstodopolling,theflowformobilephoneissimplyaterrorist,byasimpletest,calculatedinaccordancewiththeGPRSnetworkcosts0.03yuan/K,agameofcardsthatwillconsume1yuanfee(persecondpolling),isnotacceptable.Maybewecanusethemonthlyratefeemethod,butthistopichasnothingtodowithtechnology.
TheaboveproblemledtoourchoiceofSocket,whichmeanswewillnothaveawebenvironment,andmanythingswillhavetobeimplementedbyourselves:
threadmanagement,customerstatusmonitoring,objectpooling,console..........
ThenetworkpartisintendedtobeimplementedusingJavaNIO,whichisanewnetworkmonitoringmethod,andasynchronouscommunicationbasedoneventscanimproveperformance.Aftereachclientconnection,thereisaseparateSocketChanneltocommunicatewithit,andthisSocketChannelwillexistthroughouttheuser'sentirelifecycle.Iftheuserdisconnects,theservergetsthe-1andthrowstheConnectionresetexception.Bycapturingthetwofeatures,therelevantresourcescanbeclearedupaftertheuseraccidentallydisconnects.BecauseNIOisasynchronouscommunication,thereisnocomplicatedthreadmanagement.
Two,communicationprotocol
Theprojectdoesnothavecomplexcommunicationinstructions,andthenumberofcommandsislimited,butthereisakeyissuethatneedstobeconcernedabout:
traffic.Tominimizetraffic,weusebytesinsteadofstringstostoresysteminstructions,thusreducingtrafficbyhalf,suchasusingabytetoholdacard,
Thebytehighindicatesthecolor,andthebyteislowfornumbers.Ifthe0representsspades,thenthespadethreeshouldbe0x03,whichrequiresbitwiseoperation:
Intm=0;
Intn=3;
Bytecard=(byte)(m)(<<4)|(byte)n;//mleftfour,thenleftwithNoroperation
Thegameneedstopasstheuser'sintegral,whichisalargeinteger,usesfourbytestoholdthecomparison,andconvertstheintegertofourbytes:
Public,static,byte[],translateLong(long,mark)
{
Byte[]B=newbyte[4];
For(int,I=0,I,<4,i++)
{
B[i]=(byte)(mark>>>(24-I*8));
}
Returnb;
}
Theoperationtoturnfourbytesbackisasfollows:
Public,static,long,translateByte(byte[],b)
{
Intmask=0xff;
Inttemp=0;
Intres=0;
For(int,I=0,I,<4,i++)
{
Res<<=8;
Temp=b[i]&mask;
Restemp|=;
}
Returnres;
}
Threedatabaseconnectionpool
Duetotheabsenceofawebenvironment,soweneedourownimplementationofadatabaseconnectionpool,ApachehasaprojectcalledCommonsDBCP,whichisbasedonaApacheobjectpool(APACHEcommonspool)theirdatabaseconnectionpool,wecanbedirectlyusedtouse,ApacheSoftwaremaynotbethebest,butmuchbetterthanwemaywrite.
CommonsDBCPrequiresthree.Jar:
Commons-collections-3.1.jar,commons-dbcp-1.2.1.jar,commons-pool-1.2.jar
ThesethreefilescanbedownloadedundertheApache-Jakarta-commonsprojectandaddedtotheproject.
Thecodeforconstructingadatabaseconnectionpoolisasfollows:
Importjava.sql.*;
Importcom.gwnet.games.antiLord.util.*;
Importmons.dbcp.ConnectionFactory;
Importmons.dbcp.BasicDataSource;
Importmons.dbcp.DataSourceConnectionFactory;
Private,static,BasicDataSource,bds=new,BasicDataSource();
PrivatestaticConnectionFactoryfac=null;
//initializetheconnectionpool
Bds.setDriverClassName("org.postgresql.Driver");//databasedriver
Bds.setUrl("jdbc:
postgresql:
//localhost:
5432/myDB");//URLdatabase
Bds.setUsername("Postgres");//dbaaccount
Bds.setPassword("XXXXXXXX");//password
Bds.setInitialSize(100);//initializeconnectionnumber
Bds.setMaxIdle(10);//themaximumnumberofidle
Bds.setMaxWait(1000*60);//timeoutrecoverytime
Fac=newDataSourceConnectionFactory(BDS);//gettheconnectionfactory
Connection(conn=fac.createConnection);//getconnectionfromthepool.
(conn.close);//releasetheconnectionbacktothepool
Destroy/connectionpool
Bds.close();
Bds=null;
Fac=null;
Pleasehandlealltheexceptionsinoperation.
Four,theformationofPoker
Theneedtogeneraterandomcardsforusersinthegame,firstweneedtoinitializeapackofcardsinaHashmap,eachcardrepresentedbyonebyte,highrepresentativecolors,astherepresentativefigures,generatethewholedeck:
Private,static,HashMap,cards=new,HashMap();
Inttmp=0;
For(int=I=0;I<4;i++){
For(int,M=0,m,<13,m++){
Tmp=((byte)(I)(<<4)|(byte)m);//usebitoperationstructureofacard
Cards.
放置(新整数(i*13+m),新字节((字节)TMP));
}
}
卡。
把(新的整数(53),(新的字节(byte)0x4d));//大王
卡。
把(新的整数(54),(新的字节(byte)0x4e));//小王
如何随机地得到其中的N张牌呢?
我们的做法是生成一个0-55的随机数,用这个随机数作主键从HashMap中获得对象,取得之后,把该对象从队列中删除,以免重复取得。
由于java中的随机数是根据时间生成的,所以有可能导致用户得到的牌不够散,每个用户都摸到一条龙岂不是笑话?
所以在生成随机数的时候我们加入了一个大素数来作运算:
长cardid=新长((数学。
圆(数学。
()×87)%55)intvalue());
通过修改这个大素数,可以控制某个用户的牌比较好。
五、线程
实际上本系统并没有复杂的线程管理,但是我想提供一个控制台让管理员可以管理游戏主线程,可以让它停止、中段、恢复、重启动,本来的设计是管理员通过与线程一打交道,通过一去管理主线程B,但是熟悉java线程的朋友都知道,线程互相管理基本上就是不实际的,举个最简单的例子,一如何销毁B?
也许你会说调用B的destroy()方法就好了,网上很多讲解java线程的资料也确实是这么说的,但是他们都是鬼扯的,自己去看看java源代码吧,destroy()方法的实际代码如下线程:
公共无效destroy()
{
把新的nosuchmethoderror();
}
事实真相是,线程。
destroy()方法自始至终就没有被实现过。
所有写文章,教别人用这个方法销毁线程的人,都去撞墙吧,丢人丢大了。
最好的办法是一负责生成一个B并且启动它,然后B自己管理生存周期,一和B通过使用可共享的方法来通信,这是太阳推荐的做法。
六、异步消息
用户玩牌的过程中,有很多东西需要记录下来,比如记录用户的积分、等级变化,记录玩牌日志供数据统计等,当用户数量很多的时候,在数据库中记录这些信息会很耗费资源,用户玩了一局之后会可能会等待很长时间。
解决这个问题的方法是利用J2EE的消息豆来提供异步通信的机制,需要记录数据的时候,系统会封装一个值对象,发送给J2EE容器,这个操作是很快的,完成之后就返回,用户可以继续操作,不用关心消息何时被处理。
J2EE的消息框架具备如下特征:
◇消息一定会被阅读,而且只阅读一次。
JMS框架有自己的算法,把消息缓冲到硬盘,就算J2EE服务器死掉,消息也不会丢失。
◇系统采用点对点的队列消息队列,可以保证同等优先级的消息先进先出。
在JBoss4中,部署消息豆和队列队列,都比WebLogic8.1来的容易,只需要在JBoss。
XML中声明消息目的地,如果JBoss发现该目的地不存在的话,会自动建立一个,实在很简单。
七、启动与退出
为了让系统具备让人满意的性能,应该尽量多的重用对象,减少创建新对象。
比如上面提到的消息发送,我们的操作是提供一个静态类,在系统启动的时候就初始化,保持与JMS服务器的连接,系统发送消息的时候,不用再去查询JNDI和生成QueueConnectionFactory,这样可以提高系统响应速度。
Inthecaseofthedatabaseconnectionpool,wealsousethesameoperationtoinitializetheNconnectionsatboottime.Butifanyoperationisnotdoneattheclosingprocess,causesJMStothrowasocket,althoughnotwhatabigimpact,butthetotalisnotprofessional,butalsotheconnectionsinthepoolarenotreleased,mayalsocauseproblems.It'sbesttoletthesystem,likeJBossandotherconsoleprograms,beabletoperformoperationsafterctrl+c,releaseresources,andthenexit.WecandothisbyaddingaHooktotheprocess/thread,andthewindowsprogrammershouldbeveryfamiliarwithit.
Hookshouldbeathreadmethod,asfollows:
Public,class,Hook,extends,Thread
{
Public,void,run()
{
//releasethedatabaseconnection,thedestructionoftheconnectionpool
//closeconnectionwithJMS
}
}
Addtothemainthread:
Runtime.getRuntime().AddShutdownHook(new,Hook());
Then,theprocess/threadwillexecutetheHook'srunmethodwhenitexits,andcleanuptheresources.
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 网络在线游戏开发心得服务器端javaOnline game development experience server side Java 网络 在线 游戏 开发 心得 服务器端 javaOnline
![提示](https://static.bdocx.com/images/bang_tan.gif)
链接地址:https://www.bdocx.com/doc/28773739.html