Java網路程式設計四 非阻塞通訊UDP
阿新 • • 發佈:2019-01-03
轉自 http://blog.csdn.net/alangdangjia/article/details/9065845
- 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;
- publicclass NioUdpServer {
- publicstaticvoid 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
- finalint 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;
- publicclass NioUdpClient extends Thread {
- privatebyte[] sendData;
- private InetAddress serverAddr;
- privateint port;
- privateint dataLen;
- public NioUdpClient(InetAddress ip, int port, byte[] str,int len) {
- this.serverAddr = ip;
- this.sendData = str;
- this.dataLen = len;
- this.port = port;
- }
- publicstaticvoid main(String[] args) {
- // //測試字串
- byte[] bys = newbyte[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();
- }
- }
- }
- publicvoid 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");
- }
- }
- }