bundle开发----Socket通讯(Client)

   上篇记录了作为Server端bundle的实现,本文看看作为Client端如何实现一个bundle,代码改动的地方很小。

先来看看WifiBundle.java,代码如下(远程服务器地址为:192.168.0.1,端口号为:16384):

    package demo.wifi.bundle;  
      
    import java.io.IOException;    
    import java.net.SocketAddress;  
    import java.net.InetSocketAddress;  
    import java.util.logging.Level;  
    import java.util.logging.Logger;  
    import java.nio.ByteBuffer;  
    import java.nio.channels.SocketChannel;  
    import java.nio.channels.ServerSocketChannel;  
    import org.osgi.framework.BundleContext;  
    import java.nio.channels.NotYetConnectedException;  
      
      
    public class WifiBundle {  
          
        public static BundleContext bc = null;  
        private final static Logger logger = Logger.getLogger(WifiBundle.class.getName());    
        public volatile static SocketChannel socketChannel = null;  
           
        public static ServerSocketChannel serverSocketChannel;  
          
        public static boolean wifiRunningFlag = false;  
        public static boolean wifiConnectionError = false;  
      
        public static class WifiRunable implements  Runnable {    
              
            int totalSize = 0;  
            int leftSize = 0;  
            static String eventTopic = null;  
            int arrayPosition = 0;  
            boolean rtn;  
            ByteBuffer receiveBuffer = ByteBuffer.allocateDirect(1024);  
              
            public void run() {
                try {
                   // Socket connection
                   socketChannel = SocketChannel.open();  
                   SocketAddress socketAddress = new InetSocketAddress("192.168.0.1", 16384);
                
                  
                   if(!socketChannel.connect(socketAddress)) {
                       System.out.println("Wifi connection failed!"); 
                   } else {
                       System.out.println("Wifi connection OK!");
                   }
               
            
                   while (wifiRunningFlag) {  
                       receiveBuffer.clear();  
                       rtn = receivePackage(receiveBuffer, 128);    
                       if(!rtn) {  
                          receiveBuffer.clear();  
                          break;  
                       }  
                       receiveBuffer.clear();    
                       sendPackage(receiveBuffer);                       
                       receiveBuffer.clear();  
                   }  


                
                } catch (Exception ex) {
                    logger.log(Level.SEVERE, null, ex);
        
                }

             finally {
                try {
                    socketChannel.close();
                    socketChannel = null;
                    System.out.println("socketChannle closed!\n");
                } catch(Exception ex) {
                    return;
                }
    
            }
        }
        
    } 
          
      
        public static void sendPackage(ByteBuffer buffer) throws IOException {    
            try {  
                socketChannel.write(buffer);  
            } catch(IOException ex) {  
              ex.printStackTrace();  
              System.out.println("error occured in sendPackage()!");  
              wifiConnectionError = true;  
              return;  
            }  
            return;  
        }  
          
      
        public static boolean receivePackage(ByteBuffer byteBuffer, int size) throws IOException {  
              
            int arrayPos = 0;  
            int tempSize ;  
            int leftSize = size;  
            int totalSize = size;  
            byte[] tempByteArray = new byte[totalSize];   
            ByteBuffer tempBuffer = ByteBuffer.allocateDirect(1);  
              
            while((leftSize > 0) && (wifiRunningFlag == true))  {  
                try {  
                    while(((tempSize = socketChannel.read(tempBuffer)) != -1)  && (wifiRunningFlag == true) ) {       
                        tempBuffer.flip();  
                        if (tempSize == 0) {  
                            continue;  
                        } else {  
                            tempBuffer.get(tempByteArray, arrayPos, tempSize);  
                            leftSize --;  
                            arrayPos ++;  
                            if(leftSize == 0) {  
                                break;  
                            }  
                        }     
                    }     
                  } catch (IOException ex) {  
                    ex.printStackTrace();  
                    System.out.println("error occured in receivePackage()!");  
                    wifiConnectionError = true;  
                    return false;  
                }  
                  
            }  
              
            byteBuffer.put(tempByteArray, 0, size);  
              
            return true;      
        }  
                  
    }     

再来看看Activator.java,代码比较简单,只需在start和stop函数中分别开始和终止socket收发进程。
    package demo.wifi.bundle;  
      
    import org.osgi.framework.BundleActivator;  
    import org.osgi.framework.BundleContext;  
    import demo.wifi.bundle.WifiBundle.WifiRunable;  
    import demo.wifi.bundle.WifiBundle;  
      
      
    public class Activator implements BundleActivator {  
          
      
      public void start(BundleContext context) throws Exception {  
            
          System.out.println("wifi bundle started!");    
          WifiEventPublisher.bc = context;  
          WifiEventPublisher.eventRegister();  
      
            
          //start Wifi new thread  
          new Thread(new WifiRunable()).start();  
          WifiBundle.wifiRunningFlag = true;  
      }  
      
      public void stop(BundleContext context) throws Exception {  
          WifiBundle.wifiRunningFlag = false;  
          WifiEventPublisher.EventUnregister();  
          if(WifiBundle.socketChannel.isConnected()) {  
              WifiBundle.socketChannel.close();  
          }  
          System.out.println("wifi bundle stoped!");  
      }  
    }  


你可能感兴趣的:(bundle开发----Socket通讯(Client))