Java使用Socket通信传输文件的方法示例
作者:kongxx 发布时间:2023-04-16 21:52:31
标签:Java,Socket
本文实例讲述了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) {}
}
}
}
下面是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类来向服务器发送文件以及接受服务器响应文件。运行完后,分别检查服务器和客户端接收到的文件。
希望本文所述对大家java程序设计有所帮助。
0
投稿
猜你喜欢
- 本文实例讲述了C#实现TCP连接信息统计的方法。分享给大家供大家参考。具体实现方法如下:using System;using System.
- 1. 简单工厂介绍简单工厂有一个具体的工厂类,可以生产不同的产品,属于创建型设计模式。注意:简单工厂模式 不属于23种设计模式之列2. 简单
- 本文实例为大家分享了C#实现聊天窗体以及抖动的具体代码,供大家参考,具体内容如下一、聊天窗体案例1、聊天窗体的要求?(1)由两个文本框组以及
- 方式一:在所有mapper接口使用@Mapper注解@Mapper(将包中的所有接口都标注为DAO层接口)public interface
- 循环队列结构队列特点队列为一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,
- RabbitMQ作为AMQP的代表性产品,在项目中大量使用。结合现在主流的spring boot,极大简化了开发过程中所涉及到的消息通信问题
- 本文以C#为例讲解木马程序的实现过程。要实现木马服务的程序,主要实现以下几个功能:后台的运行(隐藏技术),控制码的接收与注册表的修改,下面就
- 最近IDEA打可执行Jar包搞了三天,一直失败,好好学习一下Maven-assembly,在此记录一下1. 需求项目打包,满足以下要求:1.
- 本文实例为大家分享了JDBC实现学生管理系统的具体代码,供大家参考,具体内容如下1、学生类package manage;import jav
- 概述从今天开始, 小白我将带大家开启 Java 数据结构 & 算法的新篇章.贪心算法贪心算法 (Greedy Algorithm)
- 本文实例讲述了C#使用timer实现的简单闹钟程序。分享给大家供大家参考。具体如下:当我在电脑上工作,我经常会被一些东西吸引,比如某宝,结果
- Spring Boot产生环形注入***************************APPLICATION FAILED TO STAR
- 引言前边两章说了点基础的,从这章开始,我们挖挖源码。看看RocketMQ是怎么工作的。首先呢,这个生产者就是送孩子去码头的家长,孩子们呢,就
- 在hibernate5中,有了一些新的变动: 新引导 APISpatial/GIS 支持Java 8 支持扩展 AUTO
- 图像切换器(ImageSwitcher),用于实现类似于windows操作系统下的windows照片查看器中的上一张 下一张切换图片的功能,
- 前置知识在微服务项目中,如果我们想实现服务间调用,一般会选择Feign。之前介绍过一款HTTP客户端工具Retrofit,配合SpringB
- RestTemplate简介Spring RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,RestTem
- 简介happens-before是JMM的核心概念。理解happens-before是了解JMM的关键。1、设计意图JMM的设计需要考虑两个
- 主要思路是调用系统文件管理器或者其他媒体采集资源来获取要上传的文件,然后将文件的上传进度实时展示到进度条中。主Activitypackage
- Java的List在删除元素时,一般会用list.remove(o)/remove(i)方法。在使用时,容易触碰陷阱,得到意想不到的结果。总