• 注册
  • 关于作者
    企业认证:趣记站长
    关注 6 粉丝 4 喜欢 9 内容 992
    江西省·南昌市
    聊天 送礼
    • 查看作者
    • 在J2ME中完成基于UDP协议通讯递次

        在GCF中供给了DatagramConnection和Datagram两个接口,借助他们我们可以或许在J2ME中基于UDP协议拓荒联网应用顺序。在MIDP2.0中,添加了UDPDatagramConnection这个接口,他扩展了DatagramConnection并添加了两个方法getLocalAddress()和getLocalPort()。我们知道UDP效力是不牢固的,如果你希望拓荒更牢固的联网应用的话可以或许回收SocketConnection,因为TCP效力是面向连接且牢固的。我们还必须清楚地一点是以上所说的各种连接体式款式都不是MIDP类型中规定必须完成的。因此在应用之前请参考特定设备的拓荒文档。MIDP中只需Http连接是必须支持的。

        一样,我们要获得DatagramConnection的话,

      强制和防止窗口重画
      用VB创建FTP组件(get),Visual Basic构建线程安全的Singleton,如何实现VB与EXCEL的无缝连接,vb中利用xmlhttp来下载远程文件,vb中使用正则表达式,ASP.NET中Cookie编程的基础知识,MASM-打字练习程序,用VB制作注册软件的方法,VB程序中数据库的图片处理的解决方法,用VB编写键盘拦截程序,用VB实现客户——服务器(TCP/IP)编程实例,利用Visual Basic 实现无线通讯,VB 中资源文件的多种使用技巧,VB中资源文件的具体使用方法,vb接收GPS数据源码全,VB6中使用Winsock穿越各种代理的实现(TCP协议),VB实现文字“闪入”显示的特殊效果,VB对注册表操作程序开机时运行,VB将OCX植入执行文件内,利用VB函数Dir()实现递归搜索目录
      Visual Basic

      必须经过历程Connector的open方法,其中的URL应该满足以下的形势。

      datagram://localhost:5555 这样的话泄漏显示直立了一个客户端情势的连接。在指定ip:localhost和指定端口:5555

      datagram://:5555 这样直立的是一个效力器端情势的连接,在本地的5555端口。

        直立连接后,我们可以或许经过历程DatagramConnection的newDatagram()方法构造一个Datagram,然后调用DatagramConnection的send()方法。这样数据报将会发送到指定的吸收方。歧你可以或许构建这个一个认真发送数据的Sender类。

      package com.siemens.datagramtest;

      import javax.microedition.io.Datagram;

      import javax.microedition.io.DatagramConnection;

      public class Sender extends Thread

      {

        private DatagramConnection dc;

        private String address;

        private String message;

        public Sender(DatagramConnection dc)

        {

          this.dc = dc;

          start();

        }

        public synchronized void send(String addr, String msg)

        {

          address = addr;

          message = msg;

          notify();

        }

        public synchronized void run()

        {

          while (true)

          {

            // If no client to deal, wait until one connects

            if (message == null)

            {

              try

              {

                wait();

              } catch (InterruptedException e)

              {

              }

            }

            try

            {

              byte[] bytes = message.getBytes();

              Datagram dg = null;

              // Are we a sender thread for the client ? If so then there's

              // no address parameter

              if (address == null)

              {

                dg = dc.newDatagram(bytes, bytes.length);

              } else

              {

                dg = dc.newDatagram(bytes, bytes.length, address);

                System.out.println(address);

              }

              dc.send(dg);

            } catch (Exception ioe)

            {

              ioe.printStackTrace();

            }

            // Completed client handling, return handler to pool and

            // mark for wait

            message = null;

          }

        }

      }

        注意联网的时候我们应该在其余一个线程中而不是在主线程中。

      效力器端的目的就是启动后监听指定的端口,当客户端连接曩昔后吸收数据并记录下客户端的所在,以便效力器端向客户端发送数据。

      package com.siemens.datagramtest;

      import java.io.IOException;

      import javax.microedition.io.Connector;

      import javax.microedition.io.Datagram;

      import javax.microedition.io.DatagramConnection;

      import javax.microedition.io.UDPDatagramConnection;

      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 Server 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;

        private String address;

        public Server(DatagramMIDlet m)

        {

          parent = m;

          display = Display.getDisplay(parent);

          f = new Form("Datagram Server");

          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

          {

            si.setText("Waiting for connection");

            DatagramConnection dc =(DatagramConnection)Connector.open("datagram://:5555");

           

            sender = new Sender(dc);

            while (true)

            {

              Datagram dg = dc.newDatagram(100);

              dc.receive(dg);

              address = dg.getAddress();

              si.setText("Message received - "

                  + new String(dg.getData(), 0, dg.getLength()));

            

            }

          } catch (IOException ioe)

          {

            Alert a = new Alert("Server", "Port 5000 is already taken.", null,

                AlertType.ERROR);

            a.setTimeout(Alert.FOREVER);

            a.setCommandListener(this);

            display.setCurrent(a);

          } catch (Exception e)

          {

            e.printStackTrace();

          }

        }

        public void commandAction(Command c, Displayable s)

        {

          if (c == sendCommand && !parent.isPaused())

          {

            if (address == null)

            {

              si.setText("No destination address");

            } else

            {

              sender.send(address, tf.getString());

            }

          }

          if (c == Alert.DISMISS_COMMAND)

          {

            parent.destroyApp(true);

            parent.notifyDestroyed();

          }

        }

        public void stop()

        {

        }

      }

      客户端代码则是直立连接后向效力器端发送数据,并等待吸收效力器返回的数据。

      package com.siemens.datagramtest;

      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()

        {

        }

      }

        本文的代码取自WTK demo中的例子,您可以或许参考demo中的源代码!下面给出MIDlet的代码

      package com.siemens.datagramtest;

      import javax.microedition.lcdui.Choice;

      import javax.microedition.lcdui.ChoiceGroup;

      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.midlet.MIDlet;

      public class DatagramMIDlet extends MIDlet implements CommandListener

      {

        private static final String SERVER = "Server";

        private static final String CLIENT = "Client";

        private static final String[] names = { SERVER, CLIENT };

        private static Display display;

        private Form f;

        ChoiceGroup cg;

        private boolean isPaused;

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

        private Command startCommand = new Command("Start", Command.ITEM, 1);

        public DatagramMIDlet()

        {

          display = Display.getDisplay(this);

          f = new Form("Datagram Demo");

          cg = new ChoiceGroup("Please select peer", Choice.EXCLUSIVE, names,

              null);

          f.append(cg);

          f.addCommand(exitCommand);

          f.addCommand(startCommand);

          f.setCommandListener(this);

          display.setCurrent(f);

        }

        public static Display getDisplay()

        {

          return display;

        }

        public boolean isPaused()

        {

          return isPaused;

        }

        public void startApp()

        {

          isPaused = false;

        }

        public void pauseApp()

        {

          isPaused = true;

        }

        public void destroyApp(boolean unconditional)

        {

        }

        public void commandAction(Command c, Displayable s)

        {

          if (c == exitCommand)

          {

            destroyApp(true);

            notifyDestroyed();

          } else if (c == startCommand)

          {

            String name = cg.getString(cg.getSelectedIndex());

            if (name.equals(SERVER))

            {

              Server server = new Server(this);

              server.start();

            } else

            {

              Client client = new Client(this);

              client.start();

            }

          }

        }

      }

      VB软件开发中的错误捕获及处理技术
      用VB创建FTP组件(get),Visual Basic构建线程安全的Singleton,如何实现VB与EXCEL的无缝连接,vb中利用xmlhttp来下载远程文件,vb中使用正则表达式,ASP.NET中Cookie编程的基础知识,MASM-打字练习程序,用VB制作注册软件的方法,VB程序中数据库的图片处理的解决方法,用VB编写键盘拦截程序,用VB实现客户——服务器(TCP/IP)编程实例,利用Visual Basic 实现无线通讯,VB 中资源文件的多种使用技巧,VB中资源文件的具体使用方法,vb接收GPS数据源码全,VB6中使用Winsock穿越各种代理的实现(TCP协议),VB实现文字“闪入”显示的特殊效果,VB对注册表操作程序开机时运行,VB将OCX植入执行文件内,利用VB函数Dir()实现递归搜索目录
      Visual Basic

    • 0
    • 0
    • 0
    • 70
    • 单栏布局 侧栏位置: