📄 datagramclient.java
字号:
package DatagramExample;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class DatagramClient extends MIDlet implements Runnable, CommandListener {
private Display display;
private Form f;
private StringItem si;
private TextField tf;
private boolean stop;
private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
DatagramConnection dc;
public DatagramClient() {
display = Display.getDisplay(this);
f = new Form("Socket Server");
si = new StringItem("Status:", " ");
tf = new TextField("Send:", "", 100, TextField.ANY);
f.append(tf);
f.append(si);
f.addCommand(exitCommand);
f.addCommand(sendCommand);
f.setCommandListener(this);
display.setCurrent(f);
Thread t = new Thread(this);
t.start();
}
protected void startApp() {
// TODO 自动生成方法存根
}
protected void pauseApp() {
// TODO 自动生成方法存根
}
protected void destroyApp(boolean arg0) {
// TODO 自动生成方法存根
}
public void run() {
// TODO 自动生成方法存根
try {
dc = (DatagramConnection) Connector
.open("datagram://localhost:5555");
si.setText("Connected to server");
while (true) {
Datagram dg = dc.newDatagram(100);
dc.receive(dg);
// Have we actually received something or
// is this just a timeout ?
if (dg.getLength() > 0) {
si.setText("Message received - "
+ new String(dg.getData(), 0, dg.getLength()));
}
}
} catch (ConnectionNotFoundException cnfe) {
Alert a = new Alert("Client", "Please run Server MIDlet first",
null, AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void stop() {
}
public void commandAction(Command c, Displayable d) {
// TODO 自动生成方法存根
if (c == sendCommand) {
try {
byte[] bytes = tf.getString().getBytes();
Datagram dg = null;
// Are we a sender thread for the client ? If so then there's
// no address parameter
dg = dc.newDatagram(bytes, bytes.length);
dc.send(dg);
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -