天天看點

【網絡程式設計】TCP檔案上傳TCP檔案上傳

TCP檔案上傳

原理

【網絡程式設計】TCP檔案上傳TCP檔案上傳

用戶端

package com.tx.socket.tcp.fileupload;

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

/**
 * @Auther lmy
 * @Date 2021/5/14 4:02
 * @Description 用戶端
 */
public class TcpClientDemo02 {
    public static void main(String[] args) throws Exception {
        //1.建立一個Socket連接配接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);

        //2.建立一個輸出流
        OutputStream out = socket.getOutputStream();

        //3.讀取檔案
        FileInputStream fileInputStream = new FileInputStream(new File("xzq.jpg"));

        //4.寫出檔案
        byte[] bytes = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }

        //通知伺服器,我已經結束了
        socket.shutdownOutput();//我已經傳輸完了

        //确定伺服器接收完畢,才能夠斷開連接配接
        InputStream inputStream = socket.getInputStream();
        //String byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] bytes1 = new byte[2014];
        int len1;
        while ((len1 = inputStream.read(bytes1)) != -1) {
            baos.write(bytes1, 0, len1);
        }
        System.out.println(baos.toString());

        //5.關閉資源
        baos.close();
        inputStream.close();
        fileInputStream.close();
        out.close();
        socket.close();
    }
}

           

伺服器

package com.tx.socket.tcp.fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther lmy
 * @Date 2021/5/14 4:24
 * @Description 伺服器
 */
public class TcpServerDemo02 {
    public static void main(String[] args) throws Exception {
        //1.建立伺服器
        ServerSocket serverSocket = new ServerSocket(9000);
        //2.監聽用戶端的連接配接
        Socket socket = serverSocket.accept(); //阻塞式監聽,會一直等待用戶端連接配接
        //3.擷取輸入流
        InputStream in = socket.getInputStream();
        //4.檔案輸出
        FileOutputStream fileOutputStream = new FileOutputStream(new File("xzqcopy.jpg"));
        byte[] bytes = new byte[1024];
        int len;
        while ((len = in.read(bytes)) != -1) {
            fileOutputStream.write(bytes, 0, len);
        }

        //通知用戶端我已接受完畢了
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("我接收完畢了,你可以斷開了".getBytes());

        //5.關閉資源
        fileOutputStream.close();
        in.close();
        socket.close();
        serverSocket.close();
    }
}