Kxgx.com - 移动开发网

本站快讯:
搜索: 您的位置主页>参考源码>软件源码>>阅读源码:通过J2ME程序做一个用户数据报协议连接

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

2006-11-10   来源:   作者:佚名   【 】 评论:0条


 
/*
 *
 * 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
 *
 */

 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);  
                }
              }
           }
        }
    }
}
 

Tags:  
责任编辑:
  • 请文明参与讨论,禁止漫骂攻击。 用户名:新注册)密码:匿名:
    评论总数:0 [ 查看全部 ] 网友评论
    关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 帮助