Socket实现文件传输

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42723925/article/details/81206766

Socket实现文件传输

1.客户端

通过new Socket("ip",port)连接服务端

创建文件输入流读取文件

创建返回套接字的输出流

写入文章名称,长度等属性

读取、写入文章操作

关闭流

package com.company;

import javax.xml.crypto.Data;
import java.io.*;
import java.net.Socket;

//客户端
public class Client extends Socket{
	private  final String SERVER_IP="192.168.201.104";
	private final int SERVER_PORT=8999;
	private Socket client;
	private FileInputStream fis;
	private DataOutputStream dos;

	//创建客户端,并指定接收的服务端IP和端口号
	public Client() 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 {
			Client client = new Client(); // 启动客户端连接
			client.sendFile("E:/dxn/aaa.txt"); // 传输文件
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

2服务端

启动服务端new ServerSocket(port)

接收连接服务端的客户端对象

创建返回套接字的输入流

创建文件输出流写出文件

读取文章名称,长度等属性

读取、写入文章操作

关闭流

package com.company;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FileServer extends ServerSocket{

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

        public FileServer() 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("E:/a");
                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 {
                FileServer server = new FileServer(); // 启动服务端
                server.task();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

3. 每接收到一个Socket就建立一个新的线程来处理它

package com.company;


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 = 8999; // 服务端端口

	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();
		}
	}
}


 4.DataInputStream:数据输入流     读取基本 Java 数据类型

DataOutputStream:数据输出流      写出基本 Java 数据类型

 

 

展开阅读全文

没有更多推荐了,返回首页