猿问

Java通过套接字发送和接收文件(字节[])

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


当前,程序仅创建一个空文件。我不是一名出色的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();


海绵宝宝撒
浏览 659回答 3
3回答
随时随地看视频慕课网APP

相关分类

Java
我要回答