新闻中心

EEPW首页 > 嵌入式系统 > 设计应用 > 开发MIDP联网应用程序

开发MIDP联网应用程序

作者: 时间:2012-05-07 来源:网络 收藏

为在通过游戏时显示最高分,要与服务器进行通信,由此获得最高分。这里,可以用我们介绍的HttpConnection,利用GET取得最高分。可以在游戏结束时使用以下方法。

/**

*与服务器进行通信,获取最高分。

*/

publicString[]getHighScore(){

String[]str=newString[5];

HttpConnectioncon=null;

DataInputStreamin=null;

try{

con=(HttpConnection)Connector.open(SERVER_URL);

//接收response

in=con.openDataInputStream();

intinput;

inti=0;

Strings=;

while((input=in.read())!=-1){

if((char)input=='n'){

str[i]=s;

i++;

s=;

continue;

}

s=s+(char)input;

}

}catch(IOExceptione){

e.printStackTrace();

}finally{

if(con!=null){

try{

con.close();

}catch(IOExceptione1){

e1.printStackTrace();

}

}

if(in!=null){

try{

in.close();

}catch(IOExceptione1){

e1.printStackTrace();

}

}

}

returnstr;

}

ex.12

下面是进行游戏时的操作。结束游戏时向服务器发送结束时间,即利用POST如下所示发送结束时间。然后,接收来自服务器的response最高分。可以在游戏结束时使用以下方法。

/**

*向服务器发送时间表,取得最高分

*/

publicString[]sendScore(){

String[]str=newString[5];

HttpConnectioncon=null;

DataOutputStreamout=null;

DataInputStreamin=null;

try{

con=(HttpConnection)Connector.open(SERVER_URL);

con.setRequestMethod(HttpConnection.POST);

out=con.openDataOutputStream();

//向服务器发送时间表

Stringmessage=score=+second;

byte[]messageByte=message.getBytes();

for(inti=0;i

out.writeByte(messageByte[i]);

}

out.close();

//接收response

in=con.openDataInputStream();

intinput;

inti=0;

Strings=;

while((input=in.read())!=-1){

if((char)input=='n'){

str[i]=s;

i++;

s=;

continue;

}

s=s+(char)input;

}

}catch(IOExceptione){

e.printStackTrace();

}finally{

if(con!=null){

try{

con.close();

}catch(IOExceptione1){

e1.printStackTrace();

}

}

if(out!=null){

try{

out.close();

}catch(IOExceptione1){

e1.printStackTrace();

}

}

if(in!=null){

try{

in.close();

}catch(IOExceptione1){

e1.printStackTrace();

}

}

}

returnstr;

}

ex.13

2.3.显示最高分

通过游戏和游戏结束时,都显示最高分。用以下方法显示最高分:

/**

*显示最高分

*/

publicvoidpaintHighScore(Graphicsg){

for(inti=0;i

if(highscore[i]==null)break;

g.drawString(

highscore[i],

10,

10+i*15,

Graphics.LEFT|Graphics.TOP);

}

}

ex.14

2.4.运行

完成的sourcecode如下:

•BlockApplication.java

•BlockCanvas.java

另外,服务器使用的SERVLET的sourcecode式如下:

•nec_server.zip

运行后的结果如下:

3.总结

本讲中,介绍了可以利用HTTP通信进行网络编程。利用本讲介绍的东西,能够制作简单的chat程序以及作战游戏等。请大家也试着制作一些新的独特的吧。


上一页 1 2 3 4 下一页

评论


相关推荐

技术专区

关闭