通过J2ME程序做一个用户数据报协议连接

王朝java/jsp·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

Make a UDP connection from a J2ME Program

This J2ME sample program shows how to make an UDP connection from a J2ME phone.

UDP connections as compared to HTTP connections are asynchronous and therefore lightweight. Since the consumer needs to pay for the GPRS usage charges based on the amount of data transferred from and to the phones, it is best to use UDP for many consumer based applications that are not too mUCh critical in nature. The tradeoff however is the lack of acknowledgement in UDP protocol. This can be overcome by implementing application level acknowledgement if necessary.

This free J2ME sample program illustrates how to make an UDP connection back to a server from the J2ME phone and send data back to the server. The same program can be changed to transfer data between two phones if they have static IP such as in Nextel's phones.

/*

*

* This is a free J2ME sample program

* to make UDP CONNECTION from J2ME phone to a Server

*

* @author William Alexander

* free for use as long as this comment is

* included in the program as it is

*

* More Free Java programs available for download

* at http://www.java-samples.com

*

*/

import javax.microedition.lcdui.*;

import javax.microedition.midlet.*;

import javax.microedition.io.*;

import java.util.*;

public class UDPTest extends MIDlet implements CommandListener {

static final String hostname = "203.123.12.201";

static final int serverport = 9000;

private Form mainScreen = null;

static final int sendport = 9000;

static final int receiveport = 9001;

private Form resultScreen = null;

static boolean isOver = false;

TextField message=null;

private Command okCommand = new Command("OK", Command.OK, 1);

private Command backCommand = new Command("Back", Command.BACK, 2);

private Command exitCommand = new Command("Exit", Command.EXIT, 2);

private Display myDisplay;

public UDPTest() {

myDisplay = Display.getDisplay(this);

resultScreen = new Form("Result");

resultScreen.addCommand(okCommand);

resultScreen.setCommandListener(this);

mainScreen = new Form("UDP Testing");

message=new TextField("Message:"," ",90,TextField.ANY);

// mainScreen = new List("UDP Test", List.IMPLICIT);

}

public void startApp()

throws MIDletStateChangeException {

mainScreen.append(message);

mainScreen.addCommand(okCommand);

mainScreen.addCommand(exitCommand);

mainScreen.setCommandListener(this);

myDisplay.setCurrent(mainScreen);

}

public void pauseApp() {

}

public void destroyApp(boolean unconditional) {

}

public void commandAction(Command c, Displayable d) {

String res = null;

if ((c == okCommand) && (d == mainScreen)) {

// int selected = mainScreen.getSelectedIndex();

try {

//switch (selected) {

// case 0:

res = sendRequest(message.getString());

resultScreen.append (res);

myDisplay.setCurrent(resultScreen);

// break;

// }

}

catch (Exception e) {

System.err.println(e);

}

}

if ((c == exitCommand) && (d == mainScreen)) {

notifyDestroyed();

}

if ((c == okCommand) && (d == resultScreen)) {

myDisplay.setCurrent(mainScreen);

}

}

String sendRequest(String request) {

DatagramListener dgl

= new DatagramListener("datagram://:" + receiveport);

dgl.start();

doSend("datagram://" + hostname + ":" + serverport, request);

int counter = 0;

outloop:while (!isOver) {

if (counter++ > 5) break outloop;

try {

Thread.sleep(1000);

} catch (Exception e) {

System.out.println("wake up Neo!");

}

}

isOver = false;

return dgl.data;

return "Sent";

}

void doSend(String destAddr, String msg) {

int length = msg.length();

byte[] message = new byte[length];

DatagramConnection dc = null;

System.arraycopy(msg.getBytes(), 0, message, 0, length);

String localhost = "datagram://localhost:" + sendport;

try {

dc = (DatagramConnection)Connector.open(localhost);

Datagram dobject = dc.newDatagram(message, length, destAddr);

dc.send(dobject);

} catch (Exception e) {

System.out.println("Failed to send message: " + e);

} finally {

if (dc != null) {

try {

dc.close();

} catch (Exception f) {

System.out.println("Failed to close Connector: " + f);

}

}

}

}

class DatagramListener extends Thread {

DatagramConnection dc = null;

Datagram dobject;

String data = "error";

DatagramListener(String recvAddr) {

try {

dc = (DatagramConnection)Connector.open(recvAddr);

dobject = dc.newDatagram(dc.getMaximumLength());

} catch (Exception e) {

System.out.println("Failed to initialize Connector");

}

}

public void run() {

try {

dc.receive(dobject);

data = new String(dobject.getData(), 0, dobject.getLength());

isOver = true;

} catch (Exception e) {

System.err.println("Failed to receive message:" + e);

} finally {

if (dc != null) {

try {

dc.close();

} catch (Exception f) {

System.err.println("Failed to close Connector: " + f);

}

}

}

}

}

}

(出处:http://www.knowsky.com)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航