通过同一套接字在对象之后发送文件,反之亦然

时间:2019-02-22 16:06:01

标签: java sockets

作为标题,我希望能够在发送对象后立即从客户端向服务器发送文件。

编辑:找到解决方案 由于存在重复的问题,我开发了此解决方案,希望有人会喜欢它。

public class Sender {

public static Socket send(String nodeAddress, int port, Object obj) throws IOException {
    Socket socket = new Socket(nodeAddress, port);
    OutputStream os = socket.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(obj);
    //oos.close();
    //os.close();
    //socket.close();
    return socket;
}

public static void send(Socket socket, Object obj) throws IOException {
    OutputStream os = socket.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(obj);
    //oos.close();
    //os.close();
    //socket.close();
}

public static Socket send(String nodeAddress, int port, Object obj, boolean mode) throws SocketTimeoutException, IOException {
    int timeout = 0;
    if (mode) {
        timeout = 30;
    }
    Socket socket = new Socket();
    socket.connect(new InetSocketAddress(nodeAddress, port), timeout);       //30sec timeout
    socket.setSoTimeout(timeout);                                            //30sec on subsequent request (useless?)
    OutputStream os = socket.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(obj);
    //oos.close();
    //os.close();
    //socket.close();
    return socket;
}

public static void send(Socket socket, Object obj, boolean mode) throws SocketTimeoutException, IOException {
    int timeout = 0;
    if (mode) {
        timeout = 30;
    }
    socket.setSoTimeout(timeout);                                            //30sec on subsequent request (useless?)
    OutputStream os = socket.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(obj);
    //oos.close();
    //os.close();
    //socket.close();
}

public static void sendFileTo(Socket socket, String filePath, String fileName) throws IOException {
    int n;
    try {
        String path = filePath + fileName;


        // send file
        byte[] buffer = new byte[1024];

        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
        FileInputStream fis = new FileInputStream(new File(path));      //this can throw file not found exception

        while ((n = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, n);
            dos.flush();
        }

        fis.close();

        System.out.println("File " + path + " correctly sent.");

    } catch (FileNotFoundException ex) {
        System.out.println("File does not exist");
    }

}

}

public class Receiver {

public static Object receive(Socket socket) throws IOException, ClassNotFoundException {
    InputStream is = socket.getInputStream();
    ObjectInputStream ois = new ObjectInputStream(is);

    Object obj = ois.readObject();
    if (obj == null) {
        System.out.println("null");
    }
    //is.close();
    //socket.close();
    return obj;
}


public static void receiveFileFrom(Socket socket, String filePath, String fileName, long fileSize){
    int n;
    try {
        byte[] buffer = new byte[1024];

        File f = new File(filePath);
        f.mkdir();
        filePath = filePath + fileName;
        FileOutputStream fos = new FileOutputStream(filePath);
        System.out.println("Receiving file to:\t"+filePath+" ("+fileSize+")");
        DataInputStream is = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
        //InputStream is = socket.getInputStream();            

        while (fileSize > 0 && (n = is.read(buffer, 0, (int) Math.min(buffer.length, fileSize))) != -1) {
            fos.write(buffer, 0, n);
            fileSize -= n;
        }

        fos.close();

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

}

正如善良的用户建议的那样,接收者必须事先知道fileSize。假设fileRequest是一个简单的类,允许编写文件名和文件大小。 现在可以简单地:

发件人

Socket socket = new Socket(receiverIp, port);
fileRequest request = new fileRequest(fileName, fileSize);    
Sender.send(socket, request);
Sender.sendFileTo(socket, myPath, myFile);

接收器:

ServerSocket listener = new ServerSocket(port);
Socket socket = listener.accept();
Object obj = Receiver.receive(socket);
fileRequest request = (fileRequest) obj;
Receiver.receiveFileFrom(socket, destPath, request.getFileName(), request.getFileSize());

0 个答案:

没有答案