Java通过套接字发送和接收文件(字节[]) [英] Java sending and receiving file (byte[]) over sockets

查看:40
本文介绍了Java通过套接字发送和接收文件(字节[])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to develop a very simple client / server where the client converts a file to bytes, sends it to the server, and then converts the bytes back in to a file.

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

Currently the program just creates an empty file. I'm not a fantastic Java developer so any help much appreciated.

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

This is the server part that receives what the client sends.

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();

推荐答案

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

The correct way to copy a stream in Java is as follows:

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

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

Wish I had a dollar for every time I've posted that in a forum.

这篇关于Java通过套接字发送和接收文件(字节[])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆