【问题标题】:Java: Transfer a file from server to client and from client to serverJava:将文件从服务器传输到客户端以及从客户端传输到服务器
【发布时间】:2014-11-25 01:59:04
【问题描述】:

我是一个新手,我想完成从服务器到客户端的文件传输“用它做点什么”,然后将文件发送回服务器。我使用的最基本的代码在这里:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
  public static void main(String[] args) throws IOException {
    ServerSocket servsock = new ServerSocket(123456);
    File myFile = new File("s.pdf");
    while (true) {
      Socket sock = servsock.accept();
      byte[] mybytearray = new byte[(int) myFile.length()];
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
      bis.read(mybytearray, 0, mybytearray.length);
      OutputStream os = sock.getOutputStream();
      os.write(mybytearray, 0, mybytearray.length);
      os.flush();
      sock.close();
    }
  }
}

The client module

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;

public class Main {
  public static void main(String[] argv) throws Exception {
    Socket sock = new Socket("127.0.0.1", 123456);
    byte[] mybytearray = new byte[1024];
    InputStream is = sock.getInputStream();
    FileOutputStream fos = new FileOutputStream("s.pdf");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    int bytesRead = is.read(mybytearray, 0, mybytearray.length);
    bos.write(mybytearray, 0, bytesRead);
    bos.close();
    sock.close();
  }
} 

从这个网站得到它:http://www.java2s.com/Code/Java/Network-Protocol/TransferafileviaSocket.htm

我了解这是如何工作的,但我不知道如何将文件发送回服务器。 请帮忙。

【问题讨论】:

  • 套接字是双向的。保持打开状态并从服务器读取响应。
  • 我建议你使用 HTTP 并且你的“服务器”是一个简单的 servlet。然后您只需阅读请求并回答响应,servlet API 会为您完成其余的工作(在客户端上由 HTTPURLConnection 或其他 HTTPClient 代码)。
  • @jtahlborn 那么我是否要省略服务器和客户端上的 sock.close() ,然后添加写入和读取数据的反向链?
  • @eckes 感谢您的建议,但您认为不使用 HTTP 可以解决这个问题吗?
  • @meowtwo 确定是的。在刚刚打开的服务器上是 = socket.getInputStream() 和 os = socket.getOutputStream()。从一个读取,写入另一个。它只是在生产中需要很多额外的东西才能使其可靠。

标签: java sockets client server


【解决方案1】:

我过去写过一个文件传输类,你可以在你的客户端和服务器中使用它(通过创建一个实例),并使用这些方法发送和接收文件。

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

public class FileTransferProcessor {
    Socket socket;
    InputStream is;
    FileOutputStream fos;
    BufferedOutputStream bos;
    int bufferSize;


    FileTransferProcessor(Socket client) {
        socket = client;
        is = null;
        fos = null;
        bos = null;
        bufferSize = 0;

    }

    void receiveFile(String fileName) {
        try {
            is = socket.getInputStream();
            bufferSize = socket.getReceiveBufferSize();
            System.out.println("Buffer size: " + bufferSize);
            fos = new FileOutputStream(fileName);
            bos = new BufferedOutputStream(fos);
            byte[] bytes = new byte[bufferSize];
            int count;
            while ((count = is.read(bytes)) >= 0) {
                bos.write(bytes, 0, count);
            }
            bos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void sendFile(File file) {

        FileInputStream fis;
        BufferedInputStream bis;
        BufferedOutputStream out;
        byte[] buffer = new byte[8192];
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            out = new BufferedOutputStream(socket.getOutputStream());
            int count;
            while ((count = bis.read(buffer)) > 0) {
                out.write(buffer, 0, count);

            }
            out.close();
            fis.close();
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

【讨论】:

  • 在几个方面质量很差。缓冲区不需要是文件的大小,或者它附近的任何地方:这不会扩展到大文件。 8192 字节足以满足大多数用途。 flush()close() 之前是多余的,socket.close() 在关闭其输入或输出流之后也是如此。 IOExceptions 永远不应该只是变成布尔值:它们应该被记录下来。资源应在finally 块中关闭。 try/catch 的模式然后是更多的代码是不好的做法。依赖于 try 块中代码成功的代码应该在同一个 try 块内。
  • 我同意,谢谢。我前一阵子写了这篇文章,并记得它在大多数情况下都有效,所以我没有费心去深入研究它。我会尽快根据您的建议完善它。
猜你喜欢
  • 1970-01-01
  • 2016-12-27
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多