本文转载自: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 }
上述代码会试图访问一个本地的网址,而后将其内容打印出来。