1.httpClient和ScrollView

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 [email protected] $^ -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);

}


运行结果(上下移动):

时间: 2024-10-21 07:31:32

1.httpClient和ScrollView的相关文章

Android网络(3):HttpClient作客户端,Tomcat Servlet作服务器的交互示例

前面相继介绍了Android网络编程里的Socket传输图片.HttpURLConnection,今天看HttpClient. 第一部分:JavaEE版的Eclipse配置Tomcat [备注:开发后台服务器用Eclipse的JavaEE版最好的,但单就Tomcat来说(不写jsp之类的),本文下面的服务器方面操作在普通版的Eclipse也是可以的.我这里为了和ADT-bundle分开,特意重新安个JavaEE版的Eclipse.] 1.下载Eclipse的Tomcat插件:http://www

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

查看原文:http://blog.csdn.net/sinat_29912455/article/details/51122286 1客户端连接服务器实现内部的原理 GET方式和POST方式的差别 HTTP返回请求数据的三种方式 2使用HTTP协议访问网络 3HttpCient 简单来说用HttpClient发送请求接收响应都很简单只需要五大步骤即可要牢记 4DefaultHttpClient GET方式 POST方式 5Java中使用HTTPHttpURLConnection GET方式 PO

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

套路篇 1.HttpClient是一个接口,因此无法创建它的实例,通常情况下都会创建一个DefaultHttpClient的实例 HttpClient httpClient=new DefaultHttpClient(); 2.如果想要发起一条GET请求,就创建一个HttpGet对象,并传入目标网络的对象,然后调用HtttpClient中的excute()方法: HttpGet httpGet=new HttpGet("http://www.baidu.com"); HttpRespo

Android系列之网络(一)----使用HttpClient发送HTTP请求

[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4004983.html 联系方式:[email protected] 一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 “超文本传输协议”,是一种为分布式,合作式,多媒体信息系统服务,面向应用层的协议,是Internet上目前使用最广泛的应用层协议,它基

Android零基础入门第61节:滚动视图ScrollView

原文:Android零基础入门第61节:滚动视图ScrollView 前面几期学习了ProgressBar系列组件.ViewAnimator系列组件.Picker系列组件和时间日期系列组件,接下来几期继续来学习常见的其他组件. 一.ScrollView概述 从前面的学习有的同学可能已经发现,当拥有很多内容时屏幕显示不完,显示不全的部分完全看不见.但是在实际项目里面,很多内容都不止一个屏幕宽度或高度,那怎么办呢?那就需要本节学习的ScrollView来完成. 在默认情况下,ScrollView只是

用gson和httpclient调用微信公众平台API

吐槽:微信api很无语,部分用xml,部分用json. 最近在找如何调用微信公众平台关于json相关的api比较方便,最后发现httpcliect和gson不错.如果你有更好的方式,请告诉我. 以下代码先了解如何使用gson和httpclient,有功夫再整到我的sophia里 import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.

Android ScrollView 滚动到顶部

有时候使用ScrollView,里边控件比较多的时候,打开界面,会滑到底部,如果要设置滑动到顶部,一般有两种方法 1.使用fullScrol(),scrollView.fullScroll(ScrollView.FOCUS_DOWN);滚动到底部 scrollView.fullScroll(ScrollView.FOCUS_UP);滚动到顶部 需要注意的是,该方法不能直接被调用 因为Android很多函数都是基于消息队列来同步,所以需要一部操作, addView完之后,不等于马上就会显示,而是在

HttpClient使用详解 (一)

Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性.因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入. 一.简介 HttpClient是Apache Jakarta Common下的子项目,用

SpringMVC template和HttpClient post提交

服务器的接口如果是springmvc客户端除了用springmvc提供的RestTemplate请求如下 public class RestClient { private static Logger logger = Logger.getLogger(RestClient.class); @SuppressWarnings({ rawtypes, unchecked }) public static Object post(String url, Map<string, object="