1 在服务器端使用sqllite编写数据库

常见命令是:sqlite3 tank.db

进入之后创建表:

create table tscore (

id integer primary key autoincrement,

username varchar(32) unique not null,

totalscore integer not null,

score integer not null

);

在服务器端编写程序:

#include<stdio.h>

#include<sqlite3.h>

#include<string.h>

#include<stdlib.h>

int main()

printf("Content-type:text/html\n\n");

//set Score to Database

char * queryString = getenv("QUERY_STRING");

if(queryString == NULL)

{

printf("Err:queryString is NULL");

return 0;

}

//totalscore=%d&score=%d&user=user%d

//获取参数

char *totalScore = strtok(queryString,"&");

char *score = strtok(NULL,"&");

char *username = strtok(NULL,"&");

strtok(totalScore,"=");

totalScore = strtok(NULL,"=");

strtok(score,"=");

score = strtok(NULL,"=");

//写数据库

sqlite3* db;

int ret = sqlite3_open("/usr/lib/cgi-bin/tank.db",&db);

if(ret != SQLITE_OK)

{

printf("open database error:%s",sqlite3_errstr(sqlite3_errcode(db)));

return 0;

}

char sql[2048];

sprintf(sql,"insert into tscore(username,totalScore,score) values('%s',%s,%s)",usernam|      e,totalScore,score);

ret = sqlite3_exec(db,sql,NULL,NULL,NULL);

printf("%s<br>",sql);

if(ret != SQLITE_OK)

{

printf("insert data error:%s",sqlite3_errstr(sqlite3_errcode(db)));

sqlite3_close(db);

return 0;

}

return 0;

}

编译:

sudo gcc setScore.c -o setScore.cgi -lsqlite3

注意要加上最后面的-lsqlite3,不然

设置tank.db的权限

在浏览器中输入以下链接地址:

http://192.168.28.155/cgi-bin/setScore.cgi?totalscore=100&score=1011&username=toto

网页中的输出运行结果:

tank.db中的内容如下:

2 游戏服务器端代码,用于操作数据库

#include <stdio.h>

#include <sqlite3.h>

#include <string.h>

#include <stdlib.h>

int selectCallback(void* arg,int argc,char** argv,char** argvv)

{

//argv[0] id

//argv[1] username

//argv[2] totalscore

//argv[3] score

// username&totalscore&score&....

printf("%s&%s&%s&", argv[1], argv[2], argv[3]);

return 0;

}

int main()

{

printf("Content-type:text/html\n\n");

#if 0

printf("This is cocos cgi-test\n");

// 打印环境变量

extern char** environ;

int i;

for(i=0; ;++i)

{

if(environ[i])

printf("%s\n<br>", environ[i]);

else

break;

}

#endif

// set Score to Database

char* queryString = getenv("QUERY_STRING");

if(queryString == NULL)

{

printf("Err: queryString is NULL");

return 0;

}

// totalscore=%d&score=%d&user=user%d

// 获取参数

char* totalScore = strtok(queryString, "&");

char* score = strtok(NULL, "&");

char* username = strtok(NULL, "&");

strtok(totalScore, "=");

totalScore = strtok(NULL, "=");

strtok(score, "=");

score = strtok(NULL, "=");

strtok(username, "=");

username = strtok(NULL, "=");

// 写数据库

sqlite3* db;

int ret = sqlite3_open("/usr/lib/cgi-bin/tank.db", &db);

if(ret != SQLITE_OK)

{

printf("open database error: %s", sqlite3_errstr(sqlite3_errcode(db)));

return 0;

}

char sql[2048];

sprintf(sql, "insert into tscore (username, totalscore, score) values ('%s', %s, %s)",

username, totalScore, score);

ret = sqlite3_exec(db, sql, NULL, NULL, NULL);

#if 0

printf("%s<br>", sql);

return 0;

#endif

if(ret != SQLITE_OK)

{

printf("insert data error: %s", sqlite3_errstr(sqlite3_errcode(db)));

sqlite3_close(db);

return 0;

}

sprintf(sql, "select * from tscore order by totalscore desc limit 10");

ret = sqlite3_exec(db, sql, selectCallback, NULL, NULL);

if(ret != SQLITE_OK)

{

printf("select data error: %s", sqlite3_errstr(sqlite3_errcode(db)));

sqlite3_close(db);

return 0;

}

sqlite3_close(db);

return 0;

}

Makefile文件

cfiles := $(shell find -name "*.c")

targets := $(cfiles:.c=.cgi)

all: $(targets)

%.cgi:%.c

gcc -o $@ $^ -lsqlite3

.PHONY: clean

clean:

rm *.cgi

编译:

sudo gcc setScore.c -o setScore.cgi -lsqlite3

浏览器访问:

http://192.168.28.155/cgi-bin/setScore.cgi?totalscore=90&score=121&username=toto23

较完整的服务器段代码

setScore.c

#include <stdio.h>

#include <sqlite3.h>

#include <string.h>

#include <stdlib.h>

int selectCallback(void* arg,int argc,char** argv,char** argvv)

{

//argv[0] id

//argv[1] username

//argv[2] totalscore

//argv[3] score

// username&totalscore&score&....

printf("%s&%s&%s&", argv[1], argv[2], argv[3]);

return 0;

}

int main()

{

printf("Content-type:text/html\n\n");

#if 0

printf("This is cocos cgi-test\n");

// 打印环境变量

extern char** environ;

int i;

for(i=0; ;++i)

{

if(environ[i])

printf("%s\n<br>", environ[i]);

else

break;

}

#endif

// set Score to Database

char* queryString = getenv("QUERY_STRING");

if(queryString == NULL)

{

printf("Err: queryString is NULL");

return 0;

}

// totalscore=%d&score=%d&user=user%d

// 获取参数

char* totalScore = strtok(queryString, "&");

char* score = strtok(NULL, "&");

char* username = strtok(NULL, "&");

strtok(totalScore, "=");

totalScore = strtok(NULL, "=");

strtok(score, "=");

score = strtok(NULL, "=");

strtok(username, "=");

username = strtok(NULL, "=");

// 写数据库

sqlite3* db;

int ret = sqlite3_open("/usr/lib/cgi-bin/tank.db", &db);

if(ret != SQLITE_OK)

{

printf("open database error: %s", sqlite3_errstr(sqlite3_errcode(db)));

return 0;

}

char sql[2048];

sprintf(sql, "insert into tscore (username, totalscore, score) values ('%s', %s, %s)",

username, totalScore, score);

ret = sqlite3_exec(db, sql, NULL, NULL, NULL);

#if 0

printf("%s<br>", sql);

return 0;

#endif

if(ret != SQLITE_OK)

{

printf("insert data error: %s", sqlite3_errstr(sqlite3_errcode(db)));

sqlite3_close(db);

return 0;

}

sprintf(sql, "select * from tscore order by totalscore desc limit 10");

ret = sqlite3_exec(db, sql, selectCallback, NULL, NULL);

if(ret != SQLITE_OK)

{

printf("select data error: %s", sqlite3_errstr(sqlite3_errcode(db)));

sqlite3_close(db);

return 0;

}

sqlite3_close(db);

return 0;

}

3 HttpClient的客户端:

T24HttpClient.h(Get方式)

#ifndef
__T24HttpClient_H__

#define
__T24HttpClient_H__

#include
"cocos2d.h"

#include
"cocos-ext.h"

#include
"TBack.h"

USING_NS_CC;

USING_NS_CC_EXT;

class
T24HttpClient :public
TBack

{

public:

CREATE_FUNC(T24HttpClient);

bool init();

static
CCScene * scene();

void HttpResponse(CCHttpClient*
client, CCHttpResponse*
response);

};

#endif

T24HttpClient.cpp

#include
"T24HttpClient.h"

CCScene*
T24HttpClient::scene()

{

CCScene* scene =
CCScene::create();

T24HttpClient* layer =
T24HttpClient::create();

scene->addChild(layer);

return scene;

}

bool
T24HttpClient::init()

{

TBack::init();

//向服务器发送请求(http报文)单例

CCHttpClient* client =
CCHttpClient::getInstance();

//创建一个request对象

CCHttpRequest* request =
new CCHttpRequest();

//设置访问URL

request->setUrl("http://192.168.192.130/cgi-bin/setScore.cgi?username=xxx&score=xxxx&totalscore=xxx");

request->setResponseCallback(this,
httpresponse_selector(T24HttpClient::HttpResponse));

//要对client进行release

client->release();

return
true;

}

//通过回调的方式实现

void
T24HttpClient::HttpResponse(CCHttpClient*
client, CCHttpResponse*
response)

{

if (!response->isSucceed())

{

CCLog("response error: %s",
response->getErrorBuffer());

return;

}

//获得相应的数据

std::vector<char>* data =
response->getResponseData();

std::string strData;

std::vector<char>::iterator it;

for (it = data->begin(); it != data->end(); ++it)

{

strData.push_back(*it);

}

CCLog("response data is: %s", strData.c_str());

}

运行结果:

HttpClient(POST方式);

#ifndef
__HttpClientPost_H__

#define
__HttpClientPost_H__

#include
"cocos2d.h"

#include
"cocos-ext.h"

#include
"TBack.h"

USING_NS_CC;

USING_NS_CC_EXT;

class
HttpClientPost:public
TBack

{

public:

CREATE_FUNC(HttpClientPost);

bool init();

static
CCScene* scene();

void HttpResponse(CCHttpClient*
client, CCHttpResponse*
response);

};

#endif

HttpClientPost.cpp

#include
"HttpClientPost.h"

CCScene*
HttpClientPost::scene()

{

CCScene* scene =
CCScene::create();

HttpClientPost* layer =
HttpClientPost::create();

scene->addChild(layer);

return scene;

}

bool
HttpClientPost::init()

{

TBack::init();

//向服务器发送请求(http报文)

CCHttpClient* client =
CCHttpClient::getInstance();

CCHttpRequest* req =
new CCHttpRequest;

req->setUrl("http://192.168.192.131/cgi-bin/posttest.cgi");

req->setRequestType(CCHttpRequest::kHttpPost);

req->setResponseCallback(this,
httpresponse_selector(HttpClientPost::HttpResponse));

char buf[8192];

FILE* f = fopen("btn_go_0.png","rb");

int len = fread(buf,1,8192,f);

fclose(f);

CCLOG("len=%d\n",len);

req->setRequestData((const
char*)buf,len);

client->send(req);

req->release();

return
true;

}

void
HttpClientPost::HttpResponse(CCHttpClient*
client, CCHttpResponse*
response)

{

//如果相应失败

if (!response->isSucceed())

{

//获取失败信息

CCLog("response error: %s",
response->getErrorBuffer());

return;

}

//获得相应的数据

std::vector<char>* data =
response->getResponseData();

std::string strData;

std::vector<char>::iterator it;

for (it = data->begin(); it != data->end(); ++it)

{

strData.push_back(*it);

}

CCLog("response data is:%s", strData.c_str());

}

运行结果:

2 CCScrollView案例

T25ScrollView.h

#ifndef
__T25ScrollView_H__

#define
__T25ScrollView_H__

#include
"cocos2d.h"

#include
"cocos-ext.h"

#include
"TBack.h"

USING_NS_CC;

USING_NS_CC_EXT;

class
T25ScrollView :public
TBack

{

public:

CREATE_FUNC(T25ScrollView);

bool init();

static
CCScene * scene();

bool ccTouchBegan(CCTouch *pTouch,
CCEvent *pEvent);

void ccTouchEnded(CCTouch *pTouch,
CCEvent *pEvent);

void adjustViewPos(float
dt);

CCNode* _node;

bool isSlider(CCTouch*
t);

};

#endif

T25ScrollView.cpp

#include
"T25ScrollView.h"

CCScene *T25ScrollView::scene()

{

CCScene * scene =
CCScene::create();

T25ScrollView * layer =
T25ScrollView::create();

scene->addChild(layer);

return scene;

}

bool
T25ScrollView::init()

{

TBack::init();

CCSize winSize =
CCDirector::sharedDirector()->getWinSize();

CCNode* node =
CCNode::create();

_node = node;

char buf[] =
"a";

//注意:ScrollView中的每个元素实际上都是一个精灵

for (int i = 0; i < 5; ++i)

{

//创建精灵

CCSprite* s =
CCSprite::create("HelloWorld.png");

//将精灵添加到node中去

node->addChild(s);

s->setPosition(ccp(0, winSize.height*i));

s->setAnchorPoint(ccp(0, 0));

//设置标签

CCLabelTTF* label =
CCLabelTTF::create(buf,
"Arial", 24);

buf[0]++;

s->addChild(label);

label->setPosition(ccp(winSize.width / 2, winSize.height / 2));

}

//创建ScrollView,创建的时候需要node节点

CCScrollView* view =
CCScrollView::create(winSize, node);

addChild(view);

//设置滚动试图的显示方式,下面的设置表示的是垂直滚动

view->setDirection(kCCScrollViewDirectionVertical);

//设置view的ContentSize,大小是5个精灵的高度

view->setContentSize(CCSizeMake(winSize.width, winSize.height * 5));

view->setBounceable(false);//
去掉弹性

setTouchEnabled(true);

setTouchMode(kCCTouchesOneByOne);

return
true;

}

bool
T25ScrollView::ccTouchBegan(CCTouch *pTouch,
CCEvent *pEvent)

{

return
true;

}

//判断是否滚动了

bool
T25ScrollView::isSlider(CCTouch*
t)

{

CCPoint ptCur =
t->getLocation();

CCPoint ptStart =
t->getStartLocation();

if (ptCur.getDistanceSq(ptStart) > 25)

{

return
true;

}

return
false;

}

void
T25ScrollView::adjustViewPos(float
dt)

{

//计算

CCSize winSize =
CCDirector::sharedDirector()->getWinSize();

int fitPos[] = {

0,

-winSize.height,       //向下移动一屏

-winSize.height * 2,   //向下移动两屏

-winSize.height * 3,   //向下移动三屏

-winSize.height * 4    //向下移动四屏

};

int y = _node->getPositionY();

int i;

for (i = 0; i < 5; ++i)

{

int dist = abs(fitPos[i] - y);

if (dist < winSize.height / 2)

{

break;

}

}

//创建一个点

CCPoint ptDest =
ccp(0, fitPos[i]);

//让点移动到指定的位置

_node->runAction(CCMoveTo::create(.2f, ptDest));

}

void
T25ScrollView::ccTouchEnded(CCTouch*
t, CCEvent*
e)

{

//判断点击的坐标,是哪个坐标

if (isSlider(t))

{

//调整位置

scheduleOnce(schedule_selector(T25ScrollView::adjustViewPos), 0.05f);

return;

}

//点击的代码

CCSize winSize =
CCDirector::sharedDirector()->getWinSize();

CCPoint ptWorld =
t->getLocation();

//将世界坐标转化成为本地坐标

CCPoint ptNode = _node->convertToNodeSpace(ptWorld);

int index = ptNode.y / winSize.height;

CCLog("clicked index=%d", index);

}

运行结果(上下移动):

1.httpClient和ScrollView的更多相关文章

  1. Android UI系列-----ScrollView和HorizontalScrollView

    本篇随笔将讲解一下Android当中比较常用的两个布局容器--ScrollView和HorizontalScrollView,从字面意义上来看也是非常的简单的,ScrollView就是一个可以滚动的V ...

  2. Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  3. (一)----使用HttpClient发送HTTP请求(通过get方法获取数据)

    (一)----使用HttpClient发送HTTP请求(通过get方法获取数据) 一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 “超文本传输协议”,是 ...

  4. HTTP基础与Android之(安卓与服务器通信)——使用HttpClient和HttpURLConnection

    查看原文:http://blog.csdn.net/sinat_29912455/article/details/51122286 1客户端连接服务器实现内部的原理 GET方式和POST方式的差别 H ...

  5. URLConnection和HttpClient使用入门

    本讲内容:URLConnection和HttpClient使用入门 在 Android中除了使用WebView控件访问网络以外,还有用代码方式访问网络的方法,代码方式有时候会显得更加灵活.本讲会介绍使 ...

  6. Android使用HTTP协议访问网络——HttpClient

    套路篇 1.HttpClient是一个接口,因此无法创建它的实例,通常情况下都会创建一个DefaultHttpClient的实例 HttpClient httpClient=new DefaultHt ...

  7. Android之网络----使用HttpClient发送HTTP请求(通过get方法获取数据)

    [正文] 一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 "超文本传输协议",是一种为分布式,合作式,多媒体信息系统服务,面向应用层 ...

  8. 网络相关系列之中的一个:Android中使用HttpClient发送HTTP请求

    一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 "超文本传输协议",是一种为分布式,合作式,多媒体信息系统服务,面向应用层的协议,是 ...

  9. Android网络(3):HttpClient作client,Tomcat Servlet作server的交互演示样例

    前面相继介绍了Android网络编程里的Socket传输图片.HttpURLConnection,今天看HttpClient. 第一部分:JavaEE版的Eclipse配置Tomcat [备注:开发后 ...

随机推荐

  1. 第三届“百越杯”福建省高校网络空间安全大赛_Do you know upload?

    题目在i春秋的ctf训练营 既然是上传,那就直接抓包 二话不说上来先给个00截断传个一句话助助兴 直接就成功了.... 赶紧操起菜刀去连接 进去之后发现ctf.sql是个空文件,那么flag应该在数据 ...

  2. Codeforces 700E. Cool Slogans

    Description 给定一个串 \(S\),求一个序列 \(a_i\),满足 \(a_i\) 是原串的子串,且 \(a_i\) 在 \(a_{i-1}\) 中至少出现两次,求这个序列的最大的长度 ...

  3. ●BZOJ 4826 [Hnoi2017]影魔

    题链: http://www.lydsy.com/JudgeOnline/problem.php?id=4826 题解: 主席树,单调栈 以前还没做过这种维护信息的题,感觉好奇妙. 每对相邻的两个数所 ...

  4. hdu 5591 BestCoder Round #65(博弈)

    题意: 问题描述 ZYBZYB在远足中,和同学们玩了一个“数字炸弹”游戏:由主持人心里想一个在[1,N][1,N]中的数字XX,然后玩家们轮流猜一个数字,如果一个玩家恰好猜中XX则算负,否则主持人将告 ...

  5. 【转载】 HTTP 中 GET 与 POST 的区别

    HTTP 中 GET 与 POST 的区别   GET和POST是HTTP请求的两种基本方法,要说它们的区别,接触过WEB开发的人都能说出一二. 最直观的区别就是GET把参数包含在URL中,POST通 ...

  6. C语言第五次作业——循环结构

    C语言程序设计第五次作业--循环结构(1) (一)改错题 输出华氏摄氏温度转换表:输入两个整数lower和upper,输出一张华氏摄氏温度转换表,华氏温度的取值范围是{lower,upper},每次增 ...

  7. 谈谈如何选择合适的MySQL数据类型

    MySQL数据类型选择 一 .选择原则 更小的通常更好:一般情况下选择可以正确存储数据的最小数据类型.越小的数据类型通常更快,占用磁盘,内存和CPU缓存更小. 简单就好:简单的数据类型的操作通常需要更 ...

  8. vue拦截器实现统一token,并兼容IE9验证

    项目中使用vue搭建前端页面,并通过axios请求后台api接口,完成数据交互.如果验证口令token写在在每次的接口中,也是个不小的体力活,而且也不灵活.这里分享使用vue自带拦截器,给每次请求的头 ...

  9. 配置文件错误导致jenkins无法启动 org.xmlpull.v1.XmlPullParserException: only 1.0 is supported as <?xml version not '1.1' (position: START_DOCUMENT seen <?xml version=\'1.1\'... @1:19)

    org.xmlpull.v1.XmlPullParserException: only 1.0 is supported as <?xml version not '1.1' (position ...

  10. Hibernate的条件查询的几种方式

    1. 第一种,用?占位符,如: //登录(用?占位符) public List<UserPO> LoginUser(UserPO up)throws Exception{ Session ...