Java之Socket实现文件传输

流操作

DataInputStream:数据输入流 读取基本 Java 数据类型
DataOutputStream:数据输出流 写出基本 Java 数据类型

Socket客户端

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

public class SocketClientTest extends Socket {
    private  final String SERVER_IP="127.0.0.1";
    private final int SERVER_PORT=9019;
    private Socket client;
    private FileInputStream fis;
    private DataOutputStream dos;

    //创建客户端,并指定接收的服务端IP和端口号
    public SocketClientTest() throws IOException {
        this.client=new Socket(SERVER_IP,SERVER_PORT);
        System.out.println("成功连接服务端..."+SERVER_IP);
    }

    //向服务端传输文件
    public void sendFile(String url) throws IOException {
        File file=new File(url);
        try {
            fis = new FileInputStream(file);
            //BufferedInputStream bi=new BufferedInputStream(new InputStreamReader(new FileInputStream(file),"GBK"));
            dos = new DataOutputStream(client.getOutputStream());//client.getOutputStream()返回此套接字的输出流
            //文件名、大小等属性
            dos.writeUTF(file.getName());
            dos.flush();
            dos.writeLong(file.length());
            dos.flush();
            // 开始传输文件
            System.out.println("======== 开始传输文件 ========");
            byte[] bytes = new byte[1024];
            int length = 0;

            while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
                dos.write(bytes, 0, length);
                dos.flush();
            }
            System.out.println("======== 文件传输成功 ========");
        }catch(IOException e){
            e.printStackTrace();
            System.out.println("客户端文件传输异常");
        }finally{
            fis.close();
            dos.close();
        }
    }
    public static void main(String[] args) {
        try {
            SocketClientTest client = new SocketClientTest(); // 启动客户端连接
            client.sendFile("D:\\file\\work\\test\\a.pdf"); // 传输文件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Socket服务端

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServerTest {

    private static final int SERVER_PORT = 9019; // 服务端端口
    private ServerSocket server;
    private Socket socket;
    private DataInputStream dis;
    private FileOutputStream fos;

    public SocketServerTest() throws Exception {
        server=new ServerSocket(SERVER_PORT);
    }

    public void task() throws IOException {
        System.out.println("======== 等待连接 ========");
        Socket socket = server.accept();
        System.out.println(" Ip:"+socket.getInetAddress()+"已连接");
        try {
            dis = new DataInputStream(socket.getInputStream());
            // 文件名和长度
            String fileName = dis.readUTF();
            long fileLength = dis.readLong();
            File directory = new File("D:\\file\\work");
            if(!directory.exists()) {
                directory.mkdir();
            }
            File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);

            fos = new FileOutputStream(file);
            System.out.println("file。。。。。。。。。。。。。。"+file);
            System.out.println("fileName。。。。。。。。。。。。。。"+fileName);

            System.out.println("======== 开始接收文件 ========");
            byte[] bytes = new byte[1024];
            int length = 0;
            while((length = dis.read(bytes, 0, bytes.length)) != -1) {
                fos.write(bytes, 0, length);
                fos.flush();
            }

            System.out.println("======== 文件接收成功 ========");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(fos != null)
                    fos.close();
                if(dis != null)
                    dis.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            SocketServerTest server = new SocketServerTest(); // 启动服务端
            server.task();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Socket服务端之线程优化

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server extends ServerSocket {
 
	private static final int SERVER_PORT = 9019; // 服务端端口
 
	private ServerSocket server;
 
	public Server() throws Exception {
		server=new ServerSocket(SERVER_PORT);
	}
 
	/**
	 * 使用线程处理每个客户端传输的文件
	 * @throws Exception
	 */
	public void load() throws Exception {
		while (true) {
			System.out.println("-----------等待连接-------- ");
			Socket socket = server.accept();//接收连接服务端的客户端对象
			System.out.println("ip" + socket.getInetAddress() + "已连接");
			new Thread(new Transfer(socket),"thread1").start();// 每接收到一个Socket就建立一个新的线程来处理它
			System.out.println(Thread.currentThread().getName());
		}
	}
 
	/**
	 * 处理客户端传输过来的文件线程类
	 */
	class Transfer implements Runnable {
 
		private Socket socket;
		private DataInputStream dis;
		private FileOutputStream fos;
 
		public Transfer(Socket socket) {
			this.socket = socket;
		}
 
		@Override
		public void run() {
			try {
				dis = new DataInputStream(socket.getInputStream());
 
				// 文件名和长度
				String fileName = dis.readUTF();
				long fileLength = dis.readLong();
				File directory = new File("E:/xn");
				if(!directory.exists()) {
					directory.mkdir();
				}
				File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);
				System.out.println("file"+file);
				fos = new FileOutputStream(file);
 
				// 开始接收文件
				byte[] bytes = new byte[1024];
				int length = 0;
				while((length = dis.read(bytes, 0, bytes.length)) != -1) {
					fos.write(bytes, 0, length);
					fos.flush();
				}
				System.out.println("======== 文件接收成功 [File Name:" + fileName + "] ");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if(fos != null)
						fos.close();
					if(dis != null)
						dis.close();
 
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args) {
		try {
			Server server = new Server(); // 启动服务端
			server.load();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
  • 8
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值