📄 udptest.java
字号:
//UDPTest.java
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class UDPTest extends MIDlet implements CommandListener
{
private Command exitCommand, testCmd;//命令对象
private Form form;
private TextField tfSvr,tfRecv,tfSend; //通过TextField来显示信息
private Ticker tker; //访问网络时显示滚动的标题
public UDPTest()
{
form = new Form("UDP Test");
tfSvr =new TextField("server","datagram://127.0.0.1:3000",120,TextField.URL);
tfSend =new TextField("send","abcdefg",120,TextField.ANY);
tfRecv =new TextField("receive","",120,TextField.ANY);
tker = new Ticker("Testing");
form.append(tfSvr);
form.append(tfSend);
form.append(tfRecv);
exitCommand =new Command("Exit",Command.EXIT,1);
testCmd =new Command("Send&Recv",Command.SCREEN,1);
form.addCommand(exitCommand);
form.addCommand(testCmd);
form.setCommandListener(this);
}
protected void startApp( ) throws MIDletStateChangeException
{
Display.getDisplay(this).setCurrent(form);
}
protected void pauseApp( )
{
}
protected void destroyApp( boolean p1 )
{
}
public void commandAction(Command c,Displayable d)
{
if (c ==exitCommand)
{
destroyApp(false);
notifyDestroyed();
}
else if(c ==testCmd)
{
form.setTicker(tker);
new Client(form,tfRecv, tfSvr.getString(),tfSend.getString());
}
}
private class Client extends Thread
{
private String connStr;
private String strSend , strRecv;
private Form form; //在读入数据完成后停止窗口的滚动标题
private TextField tfRecv;
public Client(Form f, TextField tf, String svr, String send)
{
form = f;
tfRecv = tf;
connStr = svr;
strSend = send;
this.start();
}
public void run()
{
try
{
strRecv = sendAndRecv(connStr, strSend);
}
catch(Exception e)
{System.out.println("error = "+e.getMessage());}
form.setTicker(null); //停止滚动标题
tfRecv.setString(strRecv);//设置接收到的字符串
}
public String sendAndRecv (String svr, String send) throws IOException
{//通过 SocketConnection 对象与TCP 服务器通信
UDPDatagramConnection uc = null;
Datagram dgSend = null; //发送数据报
Datagram dgRecv = null; //接收数据报
String recv=null;
try
{
//创建 UDPDatagramConnection 对象
uc = (UDPDatagramConnection)Connector.open(svr);
byte[] sendData = send.getBytes();
dgSend = uc.newDatagram(sendData, sendData.length);
dgRecv = uc.newDatagram(uc.getMaximumLength()); //按UDP包最大长度分配缓冲区
uc.send(dgSend);
uc.receive(dgRecv);
if(dgRecv.getLength() >0)
recv = new String(dgRecv.getData(),0,sendData.length);//创建字符串
else
recv = "Receive UDP Error";
}
catch (IOException e)
{
System.out.println("UDP error = "+e.getMessage());
}
finally
{//关闭所有对象
if (uc != null)
uc.close();
dgSend = null;
dgRecv = null;
}
return recv;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -