制作网络游戏其实不难,至少我做的是这样,用到了四个比较重要的部分:
1、HttpRequest 等一系列类和方法 (头文件以及命名空间 #include "network/HttpClient.h" using namespace cocos2d::network;)
2、用于解析Xml的几个类文件 (http://www.cocoachina.com/bbs/read.php?tid=330159&page=e&#a)
3、用Asp.net编写的WebService
4、数据库(前期用的Access,后来用的My SQL)
以我的卡牌游戏为例,当前到了我的出牌回合,我需要先摸张牌。实际上是我手机中的游戏客户端向服务器发送请求,获取当前的一张牌。
具体过程如下,首先通过HttpRequest发出一个url,也就是WebService的网址,其中包括要调用WebService的方法名与参数(如"http://localhost/WS_LL/Service.asmx/getCard?roomID=101");WebService根据参数执行方法,方法中写好对数据库的调用,获取/修改 数据库数据,将结果以XML格式返回给游戏;游戏收到WebService的反馈,将结果通过XML的一系列类去解译,得到我们要的信息,这里的话就是拿到的那张牌的ID号。
说下每个步骤稍微说一下我当初遇到的难题:
把“部分1”走通后,我确信此种方案可行。官网上有详细的教程[url]http://www.cocos.com/doc/article/index?type=cocos2d-x&url=/doc/cocos-docs-master/manual/framework/native/v3/httpclient/zh.md[/url]
“部分2” 确定我可以提取从WebService获取的信息,头文件引用这两个就行了
#include "tinyxml.h"
#include "tinystr.h"
但其他的cpp文件也是必要的。
不知道正确的使用方法是怎样的,我的方法看起来就挺山寨的,大家就仅供参考吧,下面是回调函数中的代码
void HttpManage::getCardCompleted(HttpClient *sender, HttpResponse *response)
{
std::vector<char> *buffer = response->getResponseData();
bool b = response->isSucceed();
if (!b)
{
getCard();
return;
}
std::string a = "";
for (unsigned int i = 0; i < buffer->size(); i++)
{
a += (*buffer)[i];
}
const char *p = a.c_str();
TiXmlDocument *spXmlDoc = new TiXmlDocument();
spXmlDoc->Parse(p);
TiXmlNode* pNode = NULL;
TiXmlElement *spElement = NULL;
const char * szXmlVaule = NULL;
ConstClass::MYCARD2_TYPE = std::atoi(spXmlDoc->FirstChild("int")->ToElement()->GetText());
HttpData::getCardHandler();
}
由于这个WebService得方法返回值是个整形,所以直接FristChild("int")就可以了,如果返回值是个自定义的类,那么前面都一样,提取的地方改成这样:
ConstClass::P_ID_FROM = std::atoi(spXmlDoc->FirstChild("Result")->FirstChildElement("pIDfrom")->ToElement()->GetText());
ConstClass::P_ID_TO = std::atoi(spXmlDoc->FirstChild("Result")->FirstChildElement("pIDto")->ToElement()->GetText());
ConstClass::TYPE_FROM1 = std::atoi(spXmlDoc->FirstChild("Result")->FirstChildElement("typeFrom1")->ToElement()->GetText());
ConstClass::TYPE_FROM2 = std::atoi(spXmlDoc->FirstChild("Result")->FirstChildElement("typeFrom2")->ToElement()->GetText());
ConstClass::GESS_TYPE = std::atoi(spXmlDoc->FirstChild("Result")->FirstChildElement("typeGess")->ToElement()->GetText());
ConstClass::TYPE_TO = std::atoi(spXmlDoc->FirstChild("Result")->FirstChildElement("typeTo")->ToElement()->GetText());
<webServices>
<protocols>
<add name="HttpSoap" />
<add name="HttpPost" />
<add name="HttpGet" />
</protocols>
</webServices>