/*
* DatagramClient.java Sept 22 2006
*/
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import DatagramBot;
/**
* verify the commucation with datagram server via datagram
*
* @author
*
*/
public class DatagramClient extends MIDlet implements CommandListener {
private static final String DATAGRAM_URL = "datagram_url";
private static final int MAX_LEN = 1024;
private Command exitCommand;
private TextBox textBox;
private String url;
public DatagramClient() {
initUI();
}
public void commandAction(Command arg0, Displayable arg1) {
this.destroyApp(false);
super.notifyDestroyed();
}
protected void destroyApp(boolean unconditional) {
// empty
}
/**
* main entry oh!
*/
private void initUI() {
this.url = this.getAppProperty(DATAGRAM_URL);
DatagramBot bot = new DatagramBot(url);
String content = bot.retrieveLog();
textBox = new TextBox(url, content, MAX_LEN, TextField.ANY);
exitCommand = new Command("Exit", Command.EXIT, 0);
textBox.addCommand(exitCommand);
textBox.setCommandListener(this);
}
protected void pauseApp() {
// empty
}
protected void startApp() throws MIDletStateChangeException {
Display.getDisplay(this).setCurrent(textBox);
}
}
//
/*
* DatagramBot.java Sep 22, 2006
*/
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
/**
* do datagram connection things
* @author
*
*/
public class DatagramBot {
private static final String CRLF = "/r/n";
private static final String HELLO = "hello";
private static final String SEND = ">>", RECV = "<<";
private static final int MAX_BYTE = 512;
private StringBuffer sb;
private String url;
public DatagramBot(String _url) {
this.url = _url;
sb = new StringBuffer();
try {
commu();
} catch (IOException e) {
sb.append(e.toString());
}
}
/**
* communicate with the server
*
* @throws IOException
*/
private void commu() throws IOException {
DatagramConnection dc = (DatagramConnection) Connector.open(this.url,
Connector.READ_WRITE);
Datagram outGram = dc.newDatagram(HELLO.getBytes(), HELLO.length());
dc.send(outGram);
sb.append(SEND).append(HELLO).append(CRLF);
Datagram inGram = dc.newDatagram(dc.getMaximumLength());
dc.receive(inGram);
sb.append(RECV).append(inGram.getAddress()).append(CRLF);
sb.append(RECV).append(cut(inGram.getData())).append(CRLF);
}
private String cut(byte[] inb) {
int max = inb.length;
if (max > MAX_BYTE) {
max = MAX_BYTE;
}
byte[] ob = new byte[max];
for (int i = 0; i < max; i++) {
ob[i] = inb[i];
}
return new String(ob);
}
/**
* @return
*/
public String retrieveLog() {
return sb.toString();
}
}
Java ME 开启Datagram连接
最新推荐文章于 2024-05-04 14:09:31 发布