将多个文件发送到java

时间:2017-05-12 22:58:49

标签: java sockets networking

我需要将少量文件传输到不同的计算机,每台计算机传输1个文件。现在我只能将1个文件传输到1台计算机。我的IP池中的一些计算机也可以脱机,我该如何避免异常?

此外,我在github中拥有所有代码: https://github.com/xym4uk/Diplom/tree/master/src/xym4uk/test

  

客户端

package xym4uk.test;

import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FileClient {

private static Socket sock;
private static String fileName;
private static BufferedReader stdin;
private static PrintStream ps;

public static void main(String[] args) throws IOException {

public static void sendFile(File myFile) {


    //connecting
    try {
        sock = new Socket("localhost", 4444);
        ps = new PrintStream(sock.getOutputStream());
        ps.println("1");
    } catch (Exception e) {
        System.err.println("Cannot connect to the server, try again later.");
        System.exit(1);
    }


    try {
        byte[] mybytearray = new byte[(int) myFile.length()];

        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);


        DataInputStream dis = new DataInputStream(bis);
        dis.readFully(mybytearray, 0, mybytearray.length);

        OutputStream os = sock.getOutputStream();

        //Sending file name and file size to the server
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF(myFile.getName());
        dos.writeLong(mybytearray.length);
        dos.write(mybytearray, 0, mybytearray.length);
        dos.flush();
        System.out.println("File " + myFile.getName() + " sent to Server.");
    } catch (Exception e) {
        System.err.println("File does not exist!");
    }
    DataBase.setRecord(sock.getInetAddress().toString(), myFile.getName());
    try {
        sock.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void receiveFile(String fileName) {
    try {
        sock = new Socket("localhost", 4444);
        ps = new PrintStream(sock.getOutputStream());
        ps.println("2");
        ps.println(fileName);
    } catch (Exception e) {
        System.err.println("Cannot connect to the server, try again later.");
        System.exit(1);
    }

    try {
        int bytesRead;
        InputStream in = sock.getInputStream();

        DataInputStream clientData = new DataInputStream(in);

        fileName = clientData.readUTF();
        OutputStream output = new FileOutputStream(("received_from_server_" + fileName));
        long size = clientData.readLong();
        byte[] buffer = new byte[1024];
        while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
            output.write(buffer, 0, bytesRead);
            size -= bytesRead;
        }

        output.close();
        in.close();

        System.out.println("File " + fileName + " received from Server.");
    } catch (IOException ex) {
        Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        sock.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
  

服务器

package xym4uk.test;

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

public class FileServer {

private static ServerSocket serverSocket;
private static Socket clientSocket = null;

public static void main(String[] args) throws IOException {

    try {
        serverSocket = new ServerSocket(4444);
        System.out.println("Server started.");
    } catch (Exception e) {
        System.err.println("Port already in use.");
        System.exit(1);
    }

    while (true) {
        try {
            clientSocket = serverSocket.accept();
            System.out.println("Accepted connection : " + clientSocket.getInetAddress());

            Thread t = new Thread(new CLIENTConnection(clientSocket));

            t.start();

        } catch (Exception e) {
            System.err.println("Error in connection attempt.");
        }
    }
}
}
  

ClientConnection

package xym4uk.test;

import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CLIENTConnection implements Runnable {

private Socket clientSocket;
private BufferedReader in = null;

public CLIENTConnection(Socket client) {
    this.clientSocket = client;
}

@Override
public void run() {
    try {
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String clientSelection;
        while ((clientSelection = in.readLine()) != null) {
            switch (clientSelection) {
                case "1":
                    receiveFile();
                    break;
                case "2":
                    String outGoingFileName;
                    while ((outGoingFileName = in.readLine()) != null) {
                        sendFile(outGoingFileName);
                    }
                    break;
                default:
                    System.out.println("Incorrect command received.");
                    break;
            }
            in.close();
            break;
        }

    } catch (IOException ex) {
        Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public void receiveFile() {
    try {
        int bytesRead;

        DataInputStream clientData = new DataInputStream(clientSocket.getInputStream());

        String fileName = clientData.readUTF();
        OutputStream output = new FileOutputStream(("received_from_client_" + fileName));
        long size = clientData.readLong();
        byte[] buffer = new byte[1024];
        while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
            output.write(buffer, 0, bytesRead);
            size -= bytesRead;
        }

        output.close();
        clientData.close();

        System.out.println("File "+fileName+" received from client.");
    } catch (IOException ex) {
        System.err.println("Client error. Connection closed.");
    }
}

public void sendFile(String fileName) {
    try {
        //handle file read
        File myFile = new File(fileName);
        byte[] mybytearray = new byte[(int) myFile.length()];

        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);


        DataInputStream dis = new DataInputStream(bis);
        dis.readFully(mybytearray, 0, mybytearray.length);

        //handle file send over socket
        OutputStream os = clientSocket.getOutputStream();

        //Sending file name and file size to the client
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF(myFile.getName());
        dos.writeLong(mybytearray.length);
        dos.write(mybytearray, 0, mybytearray.length);
        dos.flush();
        System.out.println("File "+fileName+" sent to client.");
    } catch (Exception e) {
        System.err.println("File does not exist!");
    }
}
}

0 个答案:

没有答案