本文轉載自:http://wing011203.cnblogs.com/java
在這篇文章裏,咱們主要討論如何使用Java實現網絡通訊,包括TCP通訊、UDP通訊、多播以及NIO。數據庫
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通訊過程當中,客戶端和服務器端的主要框架,咱們能夠發現,上述的代碼中,服務器端在任什麼時候刻,都只能處理來自客戶端的一個請求,它是串行處理的,不能並行,這和咱們印象裏的服務器處理方式不太相同,咱們能夠爲服務器添加多線程,當一個客戶端的請求進入後,咱們就建立一個線程,來處理對應的請求。框架
改善後的服務器端代碼以下:socket
多線程版本的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(); } } }
修改後的服務器端,就能夠同時處理來自客戶端的多個請求了。ide
在編程的過程當中,咱們會有「資源」的概念,例如數據庫鏈接就是一個典型的資源,爲了提高性能,咱們一般不會直接銷燬數據庫鏈接,而是使用數據庫鏈接池的方式來對多個數據庫鏈接進行管理,已實現重用的目的。對於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是一種和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端狀態。
多播採用和UDP相似的方式,它會使用D類IP地址和標準的UDP端口號,D類IP地址是指224.0.0.0到239.255.255.255之間的地址,不包括224.0.0.0。
多播會使用到的類是MulticastSocket,它有兩個方法須要關注:joinGroup和leaveGroup。
下面是一個多播的例子,Client端代碼以下
1 多播通訊客戶端 2 import java.net.*; 3 import java.io.*; 4 public class MulticastClient { 5 6 public static void main(String[] args) 7 { 8 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 9 try 10 { 11 InetAddress address = InetAddress.getByName("230.0.0.1"); 12 int port = 5678; 13 while(true) 14 { 15 String line = br.readLine(); 16 byte[] message = line.getBytes(); 17 DatagramPacket packet = new DatagramPacket(message, message.length, address, port); 18 MulticastSocket multicastSocket = new MulticastSocket(); 19 multicastSocket.send(packet); 20 if (line.equals("end")) break; 21 } 22 br.close(); 23 } 24 catch(Exception ex) 25 { 26 System.err.println(ex.getMessage()); 27 } 28 } 29 }
服務器端代碼以下:
1 多播通訊服務器端 2 import java.net.*; 3 import java.io.*; 4 public class MulticastServer { 5 6 public static void main(String[] args) 7 { 8 int port = 5678; 9 try 10 { 11 MulticastSocket multicastSocket = new MulticastSocket(port); 12 InetAddress address = InetAddress.getByName("230.0.0.1"); 13 multicastSocket.joinGroup(address); 14 byte[] buffer = new byte[1024]; 15 DatagramPacket packet = new DatagramPacket(buffer, buffer.length); 16 while(true) 17 { 18 multicastSocket.receive(packet); 19 String message = new String(buffer, packet.getLength()); 20 System.out.println(packet.getAddress().getHostName() + ":" + message); 21 if (message.equals("end")) break; 22 packet.setLength(buffer.length); 23 } 24 multicastSocket.close(); 25 } 26 catch(Exception ex) 27 { 28 System.err.println(ex.getMessage()); 29 } 30 } 31 }
NIO是JDK1.4引入的一套新的IO API,它在緩衝區管理、網絡通訊、文件存取以及字符集操做方面有了新的設計。對於網絡通訊來講,NIO使用了緩衝區和通道的概念。
下面是一個NIO的例子,和咱們上面提到的代碼風格有很大的不一樣。
1 NIO例子 2 import java.io.*; 3 import java.nio.*; 4 import java.nio.channels.*; 5 import java.nio.charset.*; 6 import java.net.*; 7 public class NewIOSample { 8 9 public static void main(String[] args) 10 { 11 String host="127.0.0.1"; 12 int port = 5678; 13 SocketChannel channel = null; 14 try 15 { 16 InetSocketAddress address = new InetSocketAddress(host,port); 17 Charset charset = Charset.forName("UTF-8"); 18 CharsetDecoder decoder = charset.newDecoder(); 19 CharsetEncoder encoder = charset.newEncoder(); 20 21 ByteBuffer buffer = ByteBuffer.allocate(1024); 22 CharBuffer charBuffer = CharBuffer.allocate(1024); 23 24 channel = SocketChannel.open(); 25 channel.connect(address); 26 27 String request = "GET / \r\n\r\n"; 28 channel.write(encoder.encode(CharBuffer.wrap(request))); 29 30 while((channel.read(buffer)) != -1) 31 { 32 buffer.flip(); 33 decoder.decode(buffer, charBuffer, false); 34 charBuffer.flip(); 35 System.out.println(charBuffer); 36 buffer.clear(); 37 charBuffer.clear(); 38 } 39 } 40 catch(Exception ex) 41 { 42 System.err.println(ex.getMessage()); 43 } 44 finally 45 { 46 if (channel != null) 47 try { 48 channel.close(); 49 } catch (IOException e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 } 53 } 54 } 55 }
上述代碼會試圖訪問一個本地的網址,而後將其內容打印出來。