TCP通信(上传文件)

package demo04;

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

public class TCPclient {
    public static void main(String[] args) throws IOException {
        //1.创建socket对象,连接服务器
        Socket s =new Socket("127.0.0.1", 8765);
        //2.通过套接字获取输出流
        OutputStream out =s.getOutputStream();
        //3.获取数据源
        FileInputStream fis =new FileInputStream("D:\\test\\aaa.png");
        //4.读数据
        int len =0;
        byte [] b =new byte [1024];
        while((len =fis.read(b))!=-1){
            //写入目的地
            out.write(b,0,len);
        }
        s.shutdownOutput();
        //接受服务器回复
        InputStream in =s.getInputStream();
        len =in.read(b);
        System.out.println(new String(b ,0,len));
        //释放资源
        fis.close();
        s.close();
    }
}
package demo04;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

import org.xml.sax.InputSource;

public class TCPserver{
    public static void main(String[] args) throws IOException {
        //1.创建服务器套接字绑定接口
        ServerSocket ser =new ServerSocket(8765);
        //2.接受套接字对象
        Socket s =ser.accept();
        //3.获取输入流
        InputStream in =s.getInputStream();
        //4.获取文件夹,如果不存在就创建
        File f =new File("f:\\aaa");
        if(!f.exists()){
            f.mkdirs();
        }
        //5.创建文件输出流
        String filename ="oracle"+System.currentTimeMillis()+new Random().nextInt(99999)+".png";
        FileOutputStream fos =new FileOutputStream(f+File.separator+filename);
        //6.写入数据
        byte  [] b =new byte [1024];
        int len =0;
        while((len =in.read(b))!=-1){
            fos.write(b,0,len);
        }
        //服务器给客服端回复(上传成功)
        OutputStream out=s.getOutputStream();
        out.write("上传成功".getBytes());
        //释放资源
        fos.close();
        s.close();
        ser.close();
    }
    
}

 

posted @ 2018-07-02 13:34  淅沥沥丶下雨  阅读(114)  评论(0编辑  收藏  举报