TCPDownloaderServer

package com.harrytsz.net;

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

public class TCPDownloaderServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9000);

        FileInputStream fileInputStream = new FileInputStream(new File("test.jpg"));

        Socket accept = serverSocket.accept();


        OutputStream outputStream = accept.getOutputStream();

        byte[] buffer = new byte[1024];
        int len;
        while((len = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }

        fileInputStream.close();
        outputStream.close();
        accept.close();
        serverSocket.close();
    }
}

TCPDownloaderClient

package com.harrytsz.net;

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

public class TCPDownloaderClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
        InputStream inputStream = socket.getInputStream();

        FileOutputStream fileOutputStream = new FileOutputStream(new File("download.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while((len = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, len);
        }

        inputStream.close();
        fileOutputStream.close();
        socket.close();
    }
}
Last modification:June 20th, 2021 at 03:15 pm
如果觉得我的文章对你有用,请随意赞赏