程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 基於Java回想之收集通訊的運用剖析

基於Java回想之收集通訊的運用剖析

編輯:關於JAVA

基於Java回想之收集通訊的運用剖析。本站提示廣大學習愛好者:(基於Java回想之收集通訊的運用剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是基於Java回想之收集通訊的運用剖析正文


TCP銜接

TCP的基本是Socket,在TCP銜接中,我們會應用ServerSocket和Socket,當客戶端和辦事器樹立銜接今後,剩下的根本就是對I/O的掌握了。

我們先來看一個簡略的TCP通訊,它分為客戶端和辦事器端。

客戶端代碼以下:

簡略的TCP客戶端
 import java.net.*;
 import java.io.*;
 public class SimpleTcpClient {

     public static void main(String[] args) throws IOException
     {
         Socket socket = null;
         BufferedReader br = null;
         PrintWriter pw = null;
         BufferedReader brTemp = null;
         try
         {
             socket = new Socket(InetAddress.getLocalHost(), 5678);
             br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             pw = new PrintWriter(socket.getOutputStream());
             brTemp = new BufferedReader(new InputStreamReader(System.in));
             while(true)
             {
                 String line = brTemp.readLine();
                 pw.println(line);
                 pw.flush();
                 if (line.equals("end")) break;
                 System.out.println(br.readLine());
             }
         }
         catch(Exception ex)
         {
             System.err.println(ex.getMessage());
         }
         finally
         {
             if (socket != null) socket.close();
             if (br != null) br.close();
             if (brTemp != null) brTemp.close();
             if (pw != null) pw.close();
         }
     }
 }

辦事器端代碼以下:

簡略版本TCP辦事器端
 import java.net.*;
 import java.io.*;
 public class SimpleTcpServer {

     public static void main(String[] args) throws IOException
     {
         ServerSocket server = null;
         Socket client = null;
         BufferedReader br = null;
         PrintWriter pw = null;
         try
         {
             server = new ServerSocket(5678);
             client = server.accept();
             br = new BufferedReader(new InputStreamReader(client.getInputStream()));
             pw = new PrintWriter(client.getOutputStream());
             while(true)
             {
                 String line = br.readLine();
                 pw.println("Response:" + line);
                 pw.flush();
                 if (line.equals("end")) break;
             }
         }
         catch(Exception ex)
         {
             System.err.println(ex.getMessage());
         }
         finally
         {
             if (server != null) server.close();
             if (client != null) client.close();
             if (br != null) br.close();
             if (pw != null) pw.close();
         }
     }
 }

這裡的辦事器的功效異常簡略,它吸收客戶端發來的新聞,然後將新聞“原封不動”的前往給客戶端。當客戶端發送“end”時,通訊停止。

下面的代碼根本上勾畫了TCP通訊進程中,客戶端和辦事器真個重要框架,我們可以發明,上述的代碼中,辦事器端在任什麼時候刻,都只能處置來自客戶真個一個要求,它是串行處置的,不克不及並行,這和我們印象裡的辦事器處置方法不太雷同,我們可認為辦事器添加多線程,當一個客戶真個要求進入後,我們就創立一個線程,來處置對應的要求。

改良後的辦事器端代碼以下:

多線程版本的TCP辦事器端
 import java.net.*;
 import java.io.*;
 public class SmartTcpServer {
     public static void main(String[] args) throws IOException
     {
         ServerSocket server = new ServerSocket(5678);
         while(true)
         {
             Socket client = server.accept();
             Thread thread = new ServerThread(client);
             thread.start();
         }
     }
 }

 class ServerThread extends Thread
 {
     private Socket socket = null;

     public ServerThread(Socket socket)
     {
         this.socket = socket;
     }

     public void run() {
         BufferedReader br = null;
         PrintWriter pw = null;
         try
         {
             br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             pw = new PrintWriter(socket.getOutputStream());
             while(true)
             {
                 String line = br.readLine();
                 pw.println("Response:" + line);
                 pw.flush();
                 if (line.equals("end")) break;
             }
         }
         catch(Exception ex)
         {
             System.err.println(ex.getMessage());
         }
         finally
         {
             if (socket != null)
                 try {
                     socket.close();
                 } catch (IOException e1) {
                     e1.printStackTrace();
                 }
             if (br != null)
                 try {
                     br.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             if (pw != null) pw.close();
         }
     }
 }

修正後的辦事器端,便可以同時處置來自客戶真個多個要求了。

在編程的進程中,我們會有“資本”的概念,例如數據庫銜接就是一個典范的資本,為了晉升機能,我們平日不會直接燒毀數據庫銜接,而是應用數據庫銜接池的方法來對多個數據庫銜接停止治理,已完成重用的目標。關於Socket銜接來講,它也是一種資本,當我們的法式須要年夜量的Socket銜接時,假如每一個銜接都須要從新樹立,那末將會是一件異常沒有用率的做法。

和數據庫銜接池相似,我們也能夠設計TCP銜接池,這裡的思緒是我們用一個數組來保持多個Socket銜接,別的一個狀況數組來描寫每一個Socket銜接能否正在應用,當法式須要Socket銜接時,我們遍歷狀況數組,掏出第一個沒被應用的Socket銜接,假如一切銜接都在應用,拋出異常。這是一種很直不雅簡略的“調劑戰略”,在許多開源或許貿易的框架中(Apache/Tomcat),都邑有相似的“資本池”。

TCP銜接池的代碼以下:

一個簡略的TCP銜接池
 import java.net.*;
 import java.io.*;
 public class TcpConnectionPool {

     private InetAddress address = null;
     private int port;
     private Socket[] arrSockets = null;
     private boolean[] arrStatus = null;
     private int count;

     public TcpConnectionPool(InetAddress address, int port, int count)
     {
         this.address = address;
         this.port = port;
         this .count = count;
         arrSockets = new Socket[count];
         arrStatus = new boolean[count];

         init();
     }

     private void init()
     {
         try
         {
             for (int i = 0; i < count; i++)
             {
                 arrSockets[i] = new Socket(address.getHostAddress(), port);
                 arrStatus[i] = false;
             }
         }
         catch(Exception ex)
         {
             System.err.println(ex.getMessage());
         }
     }

     public Socket getConnection()
     {
         if (arrSockets == null) init();
         int i = 0;
         for(i = 0; i < count; i++)
         {
             if (arrStatus[i] == false)
             {
                 arrStatus[i] = true;
                 break;
             }
         }
         if (i == count) throw new RuntimeException("have no connection availiable for now.");

         return arrSockets[i];
     }

     public void releaseConnection(Socket socket)
     {
         if (arrSockets == null) init();
         for (int i = 0; i < count; i++)
         {
             if (arrSockets[i] == socket)
             {
                 arrStatus[i] = false;
                 break;
             }
         }
     }

     public void reBuild()
     {
         init();
     }

     public void destory()
     {
         if (arrSockets == null) return;

         for(int i = 0; i < count; i++)
         {
             try
             {
                 arrSockets[i].close();
             }
             catch(Exception ex)
             {
                 System.err.println(ex.getMessage());
                 continue;
             }
         }
     }
 }

UDP銜接

UDP是一種和TCP分歧的銜接方法,它平日運用在對及時性請求很高,瞄准肯定請求不高的場所,例如在線視頻。UDP會有“丟包”的情形產生,在TCP中,假如Server沒有啟動,Client發新聞時,會報出異常,但對UDP來講,不會發生任何異常。

UDP通訊應用的兩個類時DatagramSocket和DatagramPacket,後者寄存了通訊的內容。

上面是一個簡略的UDP通訊例子,同TCP一樣,也分為Client和Server兩部門,Client端代碼以下:

UDP通訊客戶端
 import java.net.*;
 import java.io.*;
 public class UdpClient {

     public static void main(String[] args)
     {
         try
         {
             InetAddress host = InetAddress.getLocalHost();
             int port = 5678;
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             while(true)
             {
                 String line = br.readLine();
                 byte[] message = line.getBytes();
                 DatagramPacket packet = new DatagramPacket(message, message.length, host, port);
                 DatagramSocket socket = new DatagramSocket();
                 socket.send(packet);
                 socket.close();
                 if (line.equals("end")) break;
             }
             br.close();
         }
         catch(Exception ex)
         {
             System.err.println(ex.getMessage());
         }
     }
 }

Server端代碼以下:

UDP通訊辦事器端
 import java.net.*;
 import java.io.*;
 public class UdpServer {

     public static void main(String[] args)
     {
         try
         {
             int port = 5678;
             DatagramSocket dsSocket = new DatagramSocket(port);
             byte[] buffer = new byte[1024];
             DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
             while(true)
             {
                 dsSocket.receive(packet);
                 String message = new String(buffer, 0, packet.getLength());
                 System.out.println(packet.getAddress().getHostName() + ":" + message);
                 if (message.equals("end")) break;
                 packet.setLength(buffer.length);
             }
             dsSocket.close();
         }
         catch(Exception ex)
         {
             System.err.println(ex.getMessage());
         }
     }
 }

這裡,我們也假定和TCP一樣,當Client收回“end”新聞時,以為通訊停止,但其實如許的設計不是需要的,Client端可以隨時斷開,其實不須要關懷Server端狀況。
多播(Multicast)

多播采取和UDP相似的方法,它會應用D類IP地址和尺度的UDP端標語,D類IP地址是指224.0.0.0到239.255.255.255之間的地址,不包含224.0.0.0。

多播會應用到的類是MulticastSocket,它有兩個辦法須要存眷:joinGroup和leaveGroup。

上面是一個多播的例子,Client端代碼以下:

多播通訊客戶端
 import java.net.*;
 import java.io.*;
 public class MulticastClient {

     public static void main(String[] args)
     {
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         try
         {
             InetAddress address = InetAddress.getByName("230.0.0.1");
             int port = 5678;
             while(true)
             {
                 String line = br.readLine();
                 byte[] message = line.getBytes();
                 DatagramPacket packet = new DatagramPacket(message, message.length, address, port);
                 MulticastSocket multicastSocket = new MulticastSocket();
                 multicastSocket.send(packet);
                 if (line.equals("end")) break;
             }
             br.close();
         }
         catch(Exception ex)
         {
             System.err.println(ex.getMessage());
         }
     }
 }

辦事器端代碼以下:

多播通訊辦事器端
 import java.net.*;
 import java.io.*;
 public class MulticastServer {

     public static void main(String[] args)
     {
         int port = 5678;
         try
         {
             MulticastSocket multicastSocket = new MulticastSocket(port);
             InetAddress address = InetAddress.getByName("230.0.0.1");
             multicastSocket.joinGroup(address);
             byte[] buffer = new byte[1024];
             DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
             while(true)
             {
                 multicastSocket.receive(packet);
                 String message = new String(buffer, packet.getLength());
                 System.out.println(packet.getAddress().getHostName() + ":" + message);
                 if (message.equals("end")) break;
                 packet.setLength(buffer.length);
             }
             multicastSocket.close();
         }
         catch(Exception ex)
         {
             System.err.println(ex.getMessage());
         }
     }
 }

NIO(New IO)

NIO是JDK1.4引入的一套新的IO API,它在緩沖區治理、收集通訊、文件存取和字符集操作方面有了新的設計。關於收集通訊來講,NIO應用了緩沖區和通道的概念。

上面是一個NIO的例子,和我們下面提到的代碼作風有很年夜的分歧。

NIO例子
 import java.io.*;
 import java.nio.*;
 import java.nio.channels.*;
 import java.nio.charset.*;
 import java.net.*;
 public class NewIOSample {

     public static void main(String[] args)
     {
         String host="127.0.0.1";
         int port = 5678;
         SocketChannel channel = null;
         try
         {
             InetSocketAddress address = new InetSocketAddress(host,port);
             Charset charset = Charset.forName("UTF-8");
             CharsetDecoder decoder = charset.newDecoder();
             CharsetEncoder encoder = charset.newEncoder();

             ByteBuffer buffer = ByteBuffer.allocate(1024);
             CharBuffer charBuffer = CharBuffer.allocate(1024);

             channel = SocketChannel.open();
             channel.connect(address);

             String request = "GET / \r\n\r\n";
             channel.write(encoder.encode(CharBuffer.wrap(request)));

             while((channel.read(buffer)) != -1)
             {
                 buffer.flip();
                 decoder.decode(buffer, charBuffer, false);
                 charBuffer.flip();
                 System.out.println(charBuffer);
                 buffer.clear();
                 charBuffer.clear();
             }
         }
         catch(Exception ex)
         {
             System.err.println(ex.getMessage());
         }
         finally
         {
             if (channel != null)
                 try {
                     channel.close();
                 } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
         }
     }
 }

上述代碼會試圖拜訪一個當地的網址,然後將其內容打印出來。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved