文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java使用Socket通信传输文件的方法示例

2023-05-31 11:48

关注

本文实例讲述了Java使用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) {}    }  }}

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 资料下载
  • 历年真题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯