例,客户端输入商品价格,在服务器端负责游戏逻辑的处理。
服务器端代码:
Guess.jsp 这个文件放到d:/ mygameWeb目录下面
<%
String sjg=request.getParameter("jg");
int jg=(int)(Math.random()*10);
int userjg=Integer.parseInt(sjg);
if(userjg>jg)
{
out.println("sorry da le");
}
if(userjg<jg)
{
out.println("sorry xiao le");
}
if(userjg==jg)
{
out.println("right");
}
%>
J2me客户端代码:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class GuessGame
extends MIDlet
implements CommandListener, Runnable {
public Form f, f2;
public TextField tf1;
public Display d;
public Command c1, c2;
public GuessGame() {
f = new Form("商品竞猜");
f2 = new Form("竞猜结果");
c2 = new Command("返回", Command.SCREEN, 1);
f2.addCommand(c2);
f2.setCommandListener(this);
tf1 = new TextField("请输入商品价格1-9", "", 1, TextField.NUMERIC);
f.append(tf1);
c1 = new Command("确定", Command.SCREEN, 1);
f.addCommand(c1);
f.setCommandListener(this);
d = Display.getDisplay(this);
}
public void startApp() {
d.setCurrent(f);
}
public void pauseApp() {}
public void destroyApp(boolean f) {}
public void commandAction(Command c, Displayable d) {
if (c == c1) { //启动网络请求
(new Thread(this)).start();
}
if (c == c2) {
this.d.setCurrent(f);
}
}
public void run() {
try {
//打开网络连接
String url = "http://127.0.0.1/515game/Guess.jsp?jg="+ tf1.getString();
StreamConnection sc = (StreamConnection) Connector.open(url);
//获取请求结果
InputStream is = sc.openInputStream();
int tmp = 0;
String get = "";
while ( (tmp = is.read()) != -1) {
get = get + (char) (tmp);
}
for (int i = 0; i < f2.size(); i++) {
f2.delete(i);
}
f2.append(get);
d.setCurrent(f2);
//关闭网络连接
sc.close();
}
catch (Exception e) {}
}
}
|