1. 程式人生 > >Java網路程式設計四 非阻塞通訊UDP

Java網路程式設計四 非阻塞通訊UDP

轉自 http://blog.csdn.net/alangdangjia/article/details/9065845

  1. import java.io.BufferedReader;  
  2.  import java.io.ByteArrayInputStream;  
  3.  import java.io.DataInputStream;  
  4.  import java.io.IOException;  
  5.  import java.io.InputStreamReader;  
  6.  import java.net.DatagramSocket;  
  7.  import java.net.InetSocketAddress;  
  8.  import java.nio.ByteBuffer;  
  9.  import java.nio.channels.DatagramChannel;  
  10.  import java.nio.channels.SelectionKey;  
  11.  import java.nio.channels.Selector;  
  12.  import java.util.Set;  
  13.  publicclass NioUdpServer {  
  14.      publicstaticvoid main(String[] args) {  
  15.          try {  
  16.              Selector selector = Selector.open();  
  17.              DatagramChannel channel = DatagramChannel.open();  
  18.              channel.configureBlocking(false);  
  19.              DatagramSocket socket = channel.socket();  
  20.              socket.bind(new InetSocketAddress(1000));  
  21.              channel.register(selector, SelectionKey.OP_READ);  
  22.             ByteBuffer receiveBuffer = ByteBuffer.allocate(1024
    );  
  23.              finalint PACKAGE_SIZE = 10;  
  24.              while(true){  
  25.                  int n = selector.select();  
  26.                  if(n == 0){  
  27.                      continue;  
  28.                  }  
  29.                  Set<SelectionKey> readyKeys = selector.selectedKeys();  
  30.                  for(SelectionKey key : readyKeys){  
  31.                      readyKeys.remove(key);  
  32.                     if(key.isReadable()){  
  33.                          DatagramChannel dc = (DatagramChannel)key.channel();  
  34.                          InetSocketAddress client = (InetSocketAddress)dc.receive(receiveBuffer); //接收來自任意一個Client的資料報
  35.                          key.interestOps(SelectionKey.OP_READ);  
  36.                         System.out.println("client ----> IP: " + client.getAddress().getHostAddress() + ", port: " + client.getPort());  
  37.                          System.out.println("receiveBuffer.position() = " + receiveBuffer.position());  
  38.                          if(receiveBuffer.position() >= PACKAGE_SIZE){  
  39.                              receiveBuffer.flip();  
  40.                              DataInputStream dis = new DataInputStream(new ByteArrayInputStream(receiveBuffer.array()));  
  41.                              System.out.println(dis.readInt());  
  42.                              BufferedReader d = new BufferedReader(new InputStreamReader(dis));  
  43.                              System.out.println(d.readLine());  
  44.                             receiveBuffer.clear();  
  45.                          }else{  
  46.                              dc.register(selector, SelectionKey.OP_READ);  
  47.                          }  
  48.                      }//if
  49.                  }  
  50.              }//while
  51.          } catch (IOException e) {  
  52.              e.printStackTrace();  
  53.          }  
  54.      }  
  55.  }  


2. 客戶端

  1. import java.net.DatagramPacket;  
  2. import java.net.DatagramSocket;  
  3. import java.net.InetAddress;  
  4. import java.net.UnknownHostException;  
  5. publicclass NioUdpClient extends Thread {  
  6.     privatebyte[] sendData;  
  7.     private InetAddress serverAddr;  
  8.     privateint port;  
  9.     privateint dataLen;  
  10.     public NioUdpClient(InetAddress ip, int port, byte[] str,int len) {  
  11.         this.serverAddr = ip;  
  12.         this.sendData = str;  
  13.         this.dataLen = len;  
  14.         this.port = port;  
  15.     }  
  16.     publicstaticvoid main(String[] args) {  
  17. //      //測試字串
  18.         byte[] bys = newbyte[256];  
  19.         for(int i = 0; i < 256; i++){  
  20.             bys[i] = (byte) i;  
  21.         }  
  22.         for(int i = 0; i < bys.length; i++){  
  23.             System.out.println(i + "--->" + bys[i]);  
  24.         }  
  25.         while(true){  
  26.             try {  
  27.                 new Thread(new NioUdpClient(InetAddress.getLocalHost(), 1000, bys,256)).start();  
  28.             } catch (UnknownHostException e) {  
  29.                 // TODO Auto-generated catch block
  30.                 e.printStackTrace();  
  31.             }  
  32.             Thread.currentThread();  
  33.             try {  
  34.                 Thread.sleep(200);  
  35.             } catch (InterruptedException e) {  
  36.                 // TODO Auto-generated catch block
  37.                 e.printStackTrace();  
  38.             }  
  39.         }  
  40.     }  
  41.     publicvoid run() {  
  42.         try {  
  43.             System.out.println("Client: Start connecting\n");  
  44.             DatagramSocket socket = new DatagramSocket();  
  45.             DatagramPacket packet = new DatagramPacket(sendData, dataLen, serverAddr, port);  
  46.             System.out.println("Client: Sending "+dataLen+"bytes'" + new String(sendData) + "'\n");  
  47.             socket.send(packet);  
  48.             System.out.println("Client: Message sent\n");  
  49.             System.out.println("Client: Succeed!\n");  
  50.         } catch (Exception e) {  
  51.             System.out.println("Client: Error!\n");  
  52.         }  
  53.     }  
  54. }