Java Socket實戰之七 使用Socket通訊傳輸檔案
阿新 • • 發佈:2018-11-12
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
本文地址:http://blog.csdn.net/kongxx/article/details/7319410
Java Socket實戰之六 使用NIO包實現Socket通訊
前面幾篇文章介紹了使用Java的Socket程式設計和NIO包在Socket中的應用,這篇文章說說怎樣利用Socket程式設計來實現簡單的檔案傳輸。
這裡由於前面一片文章介紹了NIO在Socket中的應用,所以這裡在讀寫檔案的時候也繼續使用NIO包,所以程式碼看起來會比直接使用流的方式稍微複雜一點點。
下面的示例演示了客戶端向伺服器端傳送一個檔案,伺服器作為響應給客戶端會發一個檔案。這裡準備兩個檔案E:/test/server_send.log和E:/test/client.send.log檔案,在測試完畢後在客戶端和伺服器相同目錄下會多出兩個檔案E:/test/server_receive.log和E:/test/client.receive.log檔案。
下面首先來看看Server類,主要關注其中的sendFile和receiveFile方法。
package com.googlecode.garbagecan.test.socket.nio;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.ClosedChannelException;import java.nio.channels.FileChannel;import java.nio.channels.SelectionKey;import java.nio.channels.Selector;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.util.Iterator;import java.util.logging.Level;import java.util.logging.Logger;public class MyServer4 { private final static Logger logger = Logger.getLogger(MyServer4.class.getName()); public static void main(String[] args) { Selector selector = null; ServerSocketChannel serverSocketChannel = null; try { // Selector for incoming time requests selector = Selector.open(); // Create a new server socket and set to non blocking mode serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); // Bind the server socket to the local host and port serverSocketChannel.socket().setReuseAddress(true); serverSocketChannel.socket().bind(new InetSocketAddress(10000)); // Register accepts on the server socket with the selector. This // step tells the selector that the socket wants to be put on the // ready list when accept operations occur, so allowing multiplexed // non-blocking I/O to take place. serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // Here's where everything happens. The select method will // return when any operations registered above have occurred, the // thread has been interrupted, etc. while (selector.select() > 0) { // Someone is ready for I/O, get the ready keys Iterator<SelectionKey> it = selector.selectedKeys().iterator(); // Walk through the ready keys collection and process date requests. while (it.hasNext()) { SelectionKey readyKey = it.next(); it.remove(); // The key indexes into the selector so you // can retrieve the socket that's ready for I/O doit((ServerSocketChannel) readyKey.channel()); } } } catch (ClosedChannelException ex) { logger.log(Level.SEVERE, null, ex); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } finally { try { selector.close(); } catch(Exception ex) {} try { serverSocketChannel.close(); } catch(Exception ex) {} } } private static void doit(final ServerSocketChannel serverSocketChannel) throws IOException { SocketChannel socketChannel = null; try { socketChannel = serverSocketChannel.accept(); receiveFile(socketChannel, new File("E:/test/server_receive.log")); sendFile(socketChannel, new File("E:/test/server_send.log")); } finally { try { socketChannel.close(); } catch(Exception ex) {} } } private static void receiveFile(SocketChannel socketChannel, File file) throws IOException { FileOutputStream fos = null; FileChannel channel = null; try { fos = new FileOutputStream(file); channel = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); int size = 0; while ((size = socketChannel.read(buffer)) != -1) { buffer.flip(); if (size > 0) { buffer.limit(size); channel.write(buffer); buffer.clear(); } } } finally { try { channel.close(); } catch(Exception ex) {} try { fos.close(); } catch(Exception ex) {} } } private static void sendFile(SocketChannel socketChannel, File file) throws IOException { FileInputStream fis = null; FileChannel channel = null; try { fis = new FileInputStream(file); channel = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); int size = 0; while ((size = channel.read(buffer)) != -1) { buffer.rewind(); buffer.limit(size); socketChannel.write(buffer); buffer.clear(); } socketChannel.socket().shutdownOutput(); } finally { try { channel.close(); } catch(Exception ex) {} try { fis.close(); } catch(Exception ex) {} } }}
下面是Client程式程式碼,也主要關注sendFile和receiveFile方法
package com.googlecode.garbagecan.test.socket.nio;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.net.InetSocketAddress;import java.net.SocketAddress;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.SocketChannel;import java.util.logging.Level;import java.util.logging.Logger;public class MyClient4 { private final static Logger logger = Logger.getLogger(MyClient4.class.getName()); public static void main(String[] args) throws Exception { new Thread(new MyRunnable()).start(); } private static final class MyRunnable implements Runnable { public void run() { SocketChannel socketChannel = null; try { socketChannel = SocketChannel.open(); SocketAddress socketAddress = new InetSocketAddress("localhost", 10000); socketChannel.connect(socketAddress); sendFile(socketChannel, new File("E:/test/client_send.log")); receiveFile(socketChannel, new File("E:/test/client_receive.log")); } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); } finally { try { socketChannel.close(); } catch(Exception ex) {} } } private void sendFile(SocketChannel socketChannel, File file) throws IOException { FileInputStream fis = null; FileChannel channel = null; try { fis = new FileInputStream(file); channel = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); int size = 0; while ((size = channel.read(buffer)) != -1) { buffer.rewind(); buffer.limit(size); socketChannel.write(buffer); buffer.clear(); } socketChannel.socket().shutdownOutput(); } finally { try { channel.close(); } catch(Exception ex) {} try { fis.close(); } catch(Exception ex) {} } } private void receiveFile(SocketChannel socketChannel, File file) throws IOException { FileOutputStream fos = null; FileChannel channel = null; try { fos = new FileOutputStream(file); channel = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); int size = 0; while ((size = socketChannel.read(buffer)) != -1) { buffer.flip(); if (size > 0) { buffer.limit(size); channel.write(buffer); buffer.clear(); } } } finally { try { channel.close(); } catch(Exception ex) {} try { fos.close(); } catch(Exception ex) {} } } }}
首先執行MyServer4類啟動監聽,然後執行MyClient4類來向伺服器傳送檔案以及接受伺服器響應檔案。執行完後,分別檢查伺服器和客戶端接收到的檔案。