Java网络编程四 非阻塞通信UDP

1. 服务端

import java.io.BufferedReader;
 import java.io.ByteArrayInputStream;
 import java.io.DataInputStream;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.net.DatagramSocket;
 import java.net.InetSocketAddress;
 import java.nio.ByteBuffer;
 import java.nio.channels.DatagramChannel;
 import java.nio.channels.SelectionKey;
 import java.nio.channels.Selector;
 import java.util.Set;

 public class NioUdpServer {

     public static void main(String[] args) {
         try {
             Selector selector = Selector.open();
             DatagramChannel channel = DatagramChannel.open();
             channel.configureBlocking(false);
             DatagramSocket socket = channel.socket();
             socket.bind(new InetSocketAddress(1000));
             channel.register(selector, SelectionKey.OP_READ);
             
            ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
             final int PACKAGE_SIZE = 10;
             while(true){
                 int n = selector.select();
                 if(n == 0){
                     continue;
                 }
                 Set<SelectionKey> readyKeys = selector.selectedKeys();
                 for(SelectionKey key : readyKeys){
                     readyKeys.remove(key);
                     
                    if(key.isReadable()){
                         DatagramChannel dc = (DatagramChannel)key.channel();
                         InetSocketAddress client = (InetSocketAddress)dc.receive(receiveBuffer); //接收来自任意一个Client的数据报
                         key.interestOps(SelectionKey.OP_READ);
                         
                        System.out.println("client ----> IP: " + client.getAddress().getHostAddress() + ", port: " + client.getPort());
                         System.out.println("receiveBuffer.position() = " + receiveBuffer.position());
                         if(receiveBuffer.position() >= PACKAGE_SIZE){
                             receiveBuffer.flip();
                             DataInputStream dis = new DataInputStream(new ByteArrayInputStream(receiveBuffer.array()));
                             System.out.println(dis.readInt());
                             BufferedReader d = new BufferedReader(new InputStreamReader(dis));
                             System.out.println(d.readLine());
                             
                            receiveBuffer.clear();
                         }else{
                             dc.register(selector, SelectionKey.OP_READ);
                         }
                     }//if
                 }
             }//while
         } catch (IOException e) {
             e.printStackTrace();
         }

     }

 }


2. 客户端

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class NioUdpClient extends Thread {
	private byte[] sendData;
	private InetAddress serverAddr;
	private int port;
	private int dataLen;
	
	public NioUdpClient(InetAddress ip, int port, byte[] str,int len) {
		this.serverAddr = ip;
		this.sendData = str;
		this.dataLen = len;
		this.port = port;
	}
	
	public static void main(String[] args) {

//		//测试字符串
		byte[] bys = new byte[256];
		for(int i = 0; i < 256; i++){
			bys[i] = (byte) i;
		}
		for(int i = 0; i < bys.length; i++){
			System.out.println(i + "--->" + bys[i]);
		}
		while(true){
			try {
				new Thread(new NioUdpClient(InetAddress.getLocalHost(), 1000, bys,256)).start();
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Thread.currentThread();
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	

	public void run() {
		
		try {

			System.out.println("Client: Start connecting\n");
			DatagramSocket socket = new DatagramSocket();

			DatagramPacket packet = new DatagramPacket(sendData, dataLen, serverAddr, port);
			System.out.println("Client: Sending "+dataLen+"bytes'" + new String(sendData) + "'\n");
			socket.send(packet);
			System.out.println("Client: Message sent\n");
			System.out.println("Client: Succeed!\n");
		} catch (Exception e) {
			System.out.println("Client: Error!\n");
		}
	}
}


 

你可能感兴趣的:(Java网络编程四 非阻塞通信UDP)