【问题标题】:Java sending and receiving file (byte[]) over socketsJava 通过套接字发送和接收文件 (byte[])
【发布时间】:2020-12-21 14:17:30
【问题描述】:

我正在尝试开发一个非常简单的客户端/服务器,客户端将文件转换为字节,将其发送到服务器,然后将字节转换回文件。

目前程序只创建一个空文件。我不是一个出色的 Java 开发人员,因此非常感谢任何帮助。

这是接收客户端发送的内容的服务器部分。

ServerSocket serverSocket = null;

    serverSocket = new ServerSocket(4444);


    Socket socket = null;
    socket = serverSocket.accept();

    DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
    DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    byte[] bytes = new byte[1024];

    in.read(bytes);
    System.out.println(bytes);

    FileOutputStream fos = new FileOutputStream("C:\\test2.xml");
    fos.write(bytes);

这里是客户端部分

Socket socket = null;
    DataOutputStream out = null;
    DataInputStream in = null;
    String host = "127.0.0.1";     

    socket = new Socket(host, 4444);
    out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
    in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

    File file = new File("C:\\test.xml");
    //InputStream is = new FileInputStream(file);
    // Get the size of the file
    long length = file.length();
    if (length > Integer.MAX_VALUE) {
        System.out.println("File is too large.");
    }
    byte[] bytes = new byte[(int) length];

    //out.write(bytes);
    System.out.println(bytes);

    out.close();
    in.close();
    socket.close();

【问题讨论】:

  • 我打赌你扔掉了所有的例外......请发布整个程序。
  • 您的客户端不会向其输出流写入任何内容,并且您的服务器会忽略 read 方法的结果。谷歌“Java IO 教程”。
  • 解决方案的答案可以修改为在同一时间和同一套接字流上进行聊天和文件共享

标签: java file sockets client


【解决方案1】:

感谢您的帮助。我现在已经设法让它工作了,所以我想我会发布,以便其他人可以用来帮助他们。

服务器:

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException ex) {
            System.out.println("Can't setup server on this port number. ");
        }

        Socket socket = null;
        InputStream in = null;
        OutputStream out = null;
        
        try {
            socket = serverSocket.accept();
        } catch (IOException ex) {
            System.out.println("Can't accept client connection. ");
        }
        
        try {
            in = socket.getInputStream();
        } catch (IOException ex) {
            System.out.println("Can't get socket input stream. ");
        }

        try {
            out = new FileOutputStream("M:\\test2.xml");
        } catch (FileNotFoundException ex) {
            System.out.println("File not found. ");
        }

        byte[] bytes = new byte[16*1024];

        int count;
        while ((count = in.read(bytes)) > 0) {
            out.write(bytes, 0, count);
        }

        out.close();
        in.close();
        socket.close();
        serverSocket.close();
    }
}

和客户:

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = null;
        String host = "127.0.0.1";

        socket = new Socket(host, 4444);
        
        File file = new File("M:\\test.xml");
        // Get the size of the file
        long length = file.length();
        byte[] bytes = new byte[16 * 1024];
        InputStream in = new FileInputStream(file);
        OutputStream out = socket.getOutputStream();
        
        int count;
        while ((count = in.read(bytes)) > 0) {
            out.write(bytes, 0, count);
        }

        out.close();
        in.close();
        socket.close();
    }
}

【讨论】:

  • 没有理由通过分配整个文件大小的缓冲区来浪费空间:这不适用于大文件,或者根本不适用于超过 2GB 的文件。 8192 的缓冲区足以满足大多数用途。它也与套接字接收缓冲区大小无关。您不需要任何 flush() 调用,您只需要关闭 'out' 和 'bis'。这里有太多不必要和浪费的代码。
  • if (length > Integer.MAX_VALUE) 应该是 if (length > Long.MAX_VALUE) 因为 lengthlong 而不是 int
  • @AltianoGerung 进行此检查的原因是因为数组不能更大。但如果数组的固定大小小得多(16k),则不需要检查。我删除了这部分,至于公认的答案,它不应该是那么明显的错误。
  • @AltianoGerung A long 不能大于Long.MAX_VALUE。你的建议没有意义。
  • 我正在使用字节方法将图像文件从客户端发送到服务器。其他人是否陷入了while循环。我让它发送文件,我可以在服务器运行时打开它,但文件说它的大小为 0 字节。有什么想法吗?
【解决方案2】:

总结 EJP 的答案;使用它以获得更多流动性。 确保不要将他的代码放在更大的 try catch 中,在 .read 和 catch 块之间有更多代码,它可能会返回异常并一直跳转到外部 catch 块,最安全的选择是放置 EJPS 的 while 循环在 try catch 中,然后继续它之后的代码,例如:

int count;
byte[] bytes = new byte[4096];
try {
    while ((count = is.read(bytes)) > 0) {
        System.out.println(count);
        bos.write(bytes, 0, count);
    }
} catch ( Exception e )
{
    //It will land here....
}
// Then continue from here

编辑:^这发生在我身上,因为如果它是客户端到服务器的流,我没有意识到你需要放置 socket.shutDownOutput()!

希望这篇文章能解决你的任何问题

【讨论】:

  • 你不需要shutdownOutput()。关闭套接字具有相同的效果。如果您在复制时收到IOException,您确实想立即停止。几乎可以肯定,除了关闭它之外,您对套接字无能为力。
【解决方案3】:

Java中复制流的正确方法如下:

int count;
byte[] buffer = new byte[8192]; // or 4096, or more
while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}

希望我每次在论坛上发帖都能得到一美元。

【讨论】:

  • 谢谢!我查看了读取方法-您在哪里写了计数,那将是文件的长度,对吗?另外,当接收到字节时,您将如何反转该代码?
  • 不,count 是一个 int 变量,其中存储了每个 read() 方法调用的结果,如代码所示。接收时的代码是一样的,只是来龙去脉不同。
  • 另一种正确方法:番石榴的ByteSTreams.copy(InputStream from, OutputStream to)
  • 接收文件大小以前未知的情况下,如何在服务器上设置缓冲区大小?
  • @RubenFlores 当然,越大越好,但是超过几 K 并没有太大的好处,因为网络一次只能传输大约 1500 个字节。
【解决方案4】:

为了避免文件大小的限制,在创建文件大小为byte[] bytes = new byte[(int) length];的数组时,会导致抛出异常java.lang.OutOfMemoryError,我们可以这样做

    byte[] bytearray = new byte[1024*16];
    FileInputStream fis = null;
    try {

        fis = new FileInputStream(file);
        OutputStream output= socket.getOututStream();
        BufferedInputStream bis = new BufferedInputStream(fis);

        int readLength = -1;
        while ((readLength = bis.read(bytearray)) > 0) {
            output.write(bytearray, 0, readLength);

        }
        bis.close();
        output.close();
    }
    catch(Exception ex ){

        ex.printStackTrace();
    } //Excuse the poor exception handling...

【讨论】:

  • 新字节[100*1024];这是 100KB 而不是 100MB。
  • 即使这样也太过分了。您不需要比套接字发送缓冲区更多的缓冲,通常不超过 64k。
  • @EJP 我确实意识到 100MB 缓冲区只不过是内存浪费,多亏了你。
【解决方案5】:

这里是服务器 打开文件流并通过网络发送

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 SimpleFileServer {

  public final static int SOCKET_PORT = 5501;
  public final static String FILE_TO_SEND = "file.txt";

  public static void main (String [] args ) throws IOException {
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    OutputStream os = null;
    ServerSocket servsock = null;
    Socket sock = null;
    try {
      servsock = new ServerSocket(SOCKET_PORT);
      while (true) {
        System.out.println("Waiting...");
        try {
          sock = servsock.accept();
          System.out.println("Accepted connection : " + sock);
          // send file
          File myFile = new File (FILE_TO_SEND);
          byte [] mybytearray  = new byte [(int)myFile.length()];
          fis = new FileInputStream(myFile);
          bis = new BufferedInputStream(fis);
          bis.read(mybytearray,0,mybytearray.length);
          os = sock.getOutputStream();
          System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
          os.write(mybytearray,0,mybytearray.length);
          os.flush();
          System.out.println("Done.");
        } catch (IOException ex) {
          System.out.println(ex.getMessage()+": An Inbound Connection Was Not Resolved");
        }
        }finally {
          if (bis != null) bis.close();
          if (os != null) os.close();
          if (sock!=null) sock.close();
        }
      }
    }
    finally {
      if (servsock != null)
        servsock.close();
    }
  }
}

这里是客户端 接收通过网络发送的文件

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

public class SimpleFileClient {

  public final static int SOCKET_PORT = 5501;
  public final static String SERVER = "127.0.0.1";
  public final static String
       FILE_TO_RECEIVED = "file-rec.txt";

  public final static int FILE_SIZE = Integer.MAX_VALUE;

  public static void main (String [] args ) throws IOException {
    int bytesRead;
    int current = 0;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    Socket sock = null;
    try {
      sock = new Socket(SERVER, SOCKET_PORT);
      System.out.println("Connecting...");

      // receive file
      byte [] mybytearray  = new byte [FILE_SIZE];
      InputStream is = sock.getInputStream();
      fos = new FileOutputStream(FILE_TO_RECEIVED);
      bos = new BufferedOutputStream(fos);
      bytesRead = is.read(mybytearray,0,mybytearray.length);
      current = bytesRead;

      do {
         bytesRead =
            is.read(mybytearray, current, (mybytearray.length-current));
         if(bytesRead >= 0) current += bytesRead;
      } while(bytesRead > -1);

      bos.write(mybytearray, 0 , current);
      bos.flush();
      System.out.println("File " + FILE_TO_RECEIVED
          + " downloaded (" + current + " bytes read)");
    }
    finally {
      if (fos != null) fos.close();
      if (bos != null) bos.close();
      if (sock != null) sock.close();
    }
  }    
}

【讨论】:

【解决方案6】:

菜鸟,如果你想通过socket将文件写入服务器,那么使用fileoutputstream而不是dataoutputstream怎么样? dataoutputstream 更适合协议级别的读写。您的代码在字节读取和写入方面不是很合理。在 java io 中循环读写是必要的。而且,您使用缓冲方式。冲洗是必要的。这是一个代码示例:http://www.rgagnon.com/javadetails/java-0542.html

【讨论】:

  • 啊,这很有用,谢谢!问题 - 接收代码,静态接收的文件大小。您将如何动态设置它?有没有办法在字节数组之前发送文件长度?
  • 不能用FileOutputStream到socket上,这样用DataOutputStream也没什么问题。这个答案没有意义。
  • 并且flush()close(), 之前不是必需的,并且您提供的链接中的代码不会执行您在此处推荐的任何事情。它也不起作用。
  • @LucasAmos 这是垃圾。例如,作者没有解释客户端是如何神奇地提前知道文件大小的,或者为什么要在两端将整个文件加载到内存中。它会在空文件上失败。文件复制远比这简单。
猜你喜欢
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
  • 2012-02-12
相关资源
最近更新 更多