首頁  >  文章  >  Java  >  基於Java回顧之網路通訊的應用分析

基於Java回顧之網路通訊的應用分析

黄舟
黄舟原創
2016-12-19 14:55:221149瀏覽

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它在緩衝區管理、網路通訊、檔案存取以及字元集操作方面有了新的設計。對於網路通訊來說,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();
                 }
         }
     }
 }

上述程式碼會試圖存取一個本地的網址,然後將其內容列印出來。

 以上就是基於Java回顧之網路通訊的應用分析的內容,更多相關內容請關注PHP中文網(www.php.cn)! 


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:Java泛型下一篇:Java泛型