Socket realizes file transfer

Keywords: socket Java xml

Socket realizes file transfer

1. client

Connect to the server through new Socket("ip",port)

Create file input stream read file

Create an output stream that returns to the socket

Write article name, length and other attributes

Read and write articles

Closed flow

package com.company;

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

//Client
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;

	//Create a client and specify the IP and port number of the received server
	public Client() throws IOException{
		this.client=new Socket(SERVER_IP,SERVER_PORT);
		System.out.println("Successfully connected to the server..."+SERVER_IP);
	}

	//Transfer files to the server
	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() returns the output stream of this socket
			//File name, size and other attributes
			dos.writeUTF(file.getName());
			dos.flush();
			dos.writeLong(file.length());
			dos.flush();
			// Start file transfer
			System.out.println("======== Start file transfer ========");
			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("======== File transfer successful ========");
		}catch(IOException e){
			e.printStackTrace();
			System.out.println("Client file transfer exception");
		}finally{
			fis.close();
			dos.close();
		}
	}
	public static void main(String[] args) {
		try {
			Client client = new Client(); // Start client connection
			client.sendFile("E:/dxn/aaa.txt"); // transfer files
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

2 server side

Start the server new ServerSocket(port)

Receive the client object connecting to the server

Create an input stream to return to the socket

Create file output stream write out file

Read article name, length and other attributes

Read and write articles

Closed flow

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; // Server port
        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("======== Waiting for connection ========");
            Socket socket = server.accept();
            System.out.println(" Ip:"+socket.getInetAddress()+"Connected");
            try {
                dis = new DataInputStream(socket.getInputStream());
                // File name and length
                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("======== Start receiving files ========");
                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 received successfully ========");
                } 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(); // Start server
                server.task();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

3. Every time a Socket is received, a new thread is created to handle it

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; // Server port

	private ServerSocket server;

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

	/**
	 * Use threads to process files transferred by each client
	 * @throws Exception
	 */
	public void load() throws Exception {
		while (true) {
			System.out.println("-----------Waiting for connection-------- ");
			Socket socket = server.accept();//Receive the client object connecting to the server
			System.out.println("ip" + socket.getInetAddress() + "Connected");
			new Thread(new Transfer(socket),"thread1").start();// Every time a Socket is received, a new thread is created to handle it
			System.out.println(Thread.currentThread().getName());
		}
	}

	/**
	 * Handle the file thread class transferred from the client
	 */
	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());

				// File name and length
				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);

				// Start receiving files
				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 received successfully [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(); // Start server
			server.load();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


4.DataInputStream: read basic Java data type from data input stream

DataOutputStream: data output stream writes out basic Java data types

 

 

Posted by irandoct on Fri, 31 Jan 2020 11:38:13 -0800