05_tcp從客戶端發送文件到服務端(圖片)

package com.baidu.tcp;

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

/**
 * 服務器端
 */
public class ServerDemo1 {
    public static void main(String[] args) {
        FileOutputStream fos=null;
        OutputStream os=null;
        //建立服務器端套接字
        try {
            ServerSocket ss=new ServerSocket(9999);
            //監聽客戶端
            Socket socket=ss.accept();
            //得到客戶端通道輸入流
            InputStream is=socket.getInputStream();
            //建立字節輸出流關聯文件存儲地
            fos=new FileOutputStream("h:\\copy.mp4");
            //讀寫存入
            byte[] buf=new byte[1024*8];
            int len=0;
            while((len=is.read(buf))!=-1){
                fos.write(buf);
                fos.flush();
            }
            
            //給客戶端以反饋信息
            os=socket.getOutputStream();
            os.write("文件上傳成功!".getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                //關閉資源
                os.close();
                fos.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}

//=======================================================
package com.baidu.tcp;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 客戶端
 */
public class ClientDemo1 {
    public static void main(String[] args) {
        //1.獲取客戶端套接字
        Socket socket=null;
        try {
            socket=new Socket("localhost",9999);
            //得到通道輸出流
            OutputStream os=socket.getOutputStream();
            //建立客戶端輸入流關聯上傳文件
            FileInputStream fis=new FileInputStream("E:\\我的做品\\Lose You.mp4");
            byte[] buf=new byte[1024*8];
            int len=0;
            while((len=fis.read(buf))!=-1){
                os.write(buf,0,len);
                os.flush();
            }
            //告知客戶端文件上傳完畢
            socket.shutdownOutput();;
            //得到服務器端的反饋信息
            InputStream is=socket.getInputStream();
            byte[] buf1=new byte[1024];
            int len1=0;
            while((len1=is.read(buf1))!=-1){
                System.out.println(new String(buf1,0,len1));
            }
            is.close();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
相關文章
相關標籤/搜索