java socket传输_java socket 文件传输

本文介绍了使用Java Socket实现文件传输的过程,包括Server端的多线程并发处理和Client端的文件发送。代码示例展示了如何创建Server和Client,以及如何进行文件的读取和写入。在实际应用中,文件传输可能需要进行文件大小校验和MD5校验以确保文件完整性。
摘要由CSDN通过智能技术生成

闲着无聊,写了一个基于java的socket文件传输。

是这样设计的:

1、Server

提供文件传输的server服务器端,接收client发送过来的文件。

提供多线程并发处理,能同时处理多个client的文件传输请求。

2、Client

根据提供的参数指定的server以及本地文件的路径,进行文件传输

client的代码

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.net.InetAddress;

import java.net.InetSocketAddress;

import java.net.Socket;

import java.net.SocketAddress;

import org.apache.commons.io.IOUtils;

import org.apache.commons.lang.StringUtils;

import org.apache.log4j.Logger;

public class FileClient {

private static final Logger LOGGER = Logger.getLogger(FileClient.class);

private Socket socket;

public void sendFile(File file, String host, int port) throws IOException {

if (!file.exists() || !file.isFile()) {

throw new IllegalArgumentException("file : " + file

+ " is not a valid file!");

}

connect(host, port);

sendFile(file);

close();

}

private void sendFile(File file) throws IOException {

BufferedOutputStream fileOutput = new BufferedOutputStream(

socket.getOutputStream());

BufferedInputStream input = new BufferedInputStream(

new FileInputStream(file));

IOUtils.copy(input, fileOutput);

fileOutput.flush();

IOUtils.closeQuietly(input);

IOUtils.closeQuietly(fileOutput);

}

private void close() throws IOException {

if (isConnected()) {

socket.close();

}

}

private boolean isConnected() {

return null != socket && socket.isConnected() && !socket.isClosed();

}

private void connect(String host, int port) throws IOException {

if (isConnected()) {

return;

}

socket = new Socket();

socket.setKeepAlive(true);

socket.setReuseAddress(true);

InetAddress addr = InetAddress.getByName(host);

SocketAddress endpoint = new InetSocketAddress(addr, port);

socket.connect(endpoint);

}

/**

* @param args

*/

public stat

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值