client.java

来自「《J2ME实用教程》 源文件下载 本书没有仅仅局限于J2ME单机游戏的开发」· Java 代码 · 共 87 行

JAVA
87
字号
package datagram;

import java.io.IOException;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
public class Client implements Runnable, CommandListener
{
private DatagramMIDlet parent;
private Display display;
private Form f;
private StringItem si;
private TextField tf;
private Command sendCommand = new Command("Send", Command.ITEM, 1);
Sender sender;
public Client(DatagramMIDlet m)
{
parent = m;
display = Display.getDisplay(parent);
f = new Form("Datagram Client");
si = new StringItem("Status:", " ");
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(sendCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public void start()
{
Thread t = new Thread(this);
t.start();
}
public void run()
{
 
try
{
DatagramConnection dc = (DatagramConnection) Connector
.open("datagram://localhost:5555");
si.setText("Connected to server");
sender = new Sender(dc);
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 commandAction(Command c, Displayable s)
{
if (c == sendCommand && !parent.isPaused())
{
sender.send(null, tf.getString());
}
}
public void stop()
{
}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?