通过TCP协议,完成客户端上传文件到服务器端

要求上传各种类型文件,就不能使用包装流再进行包装了;
边读编写即可,需要创建数据缓冲区;
复制文件采用System.currentTimeMillis()方法来命名,就不会重复了;

客户端:
import java.io.*;
import java.net.Socket;

public class TCPClient {
    public static void main(String[] args) throws IOException {
        //7、编写程序,通过TCP协议,完成客户端上传文件到服务器端。

        Socket sk = new Socket("192.168.10.103",6666);
        OutputStream out = sk.getOutputStream();
        //包装输出流;

        FileInputStream in = new FileInputStream("Msg.txt");
        int len=0;
        byte[] bytes = new byte[1024];
        while ((len=in.read(bytes))!=-1){
            out.write(bytes,0,len);
            out.flush();
        }

        sk.close();

    }
}

服务端:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(6666);
        System.out.println("服务器正常开启!");
        //侦听客户端,连接传入之前处于阻塞状态;
        Socket sk = ss.accept();
        InputStream in = sk.getInputStream();
        FileOutputStream out = new FileOutputStream(System.currentTimeMillis() + "副本Msg.txt");
        int len=0;
        byte[] bytes = new byte[1024];
        while ((len=in.read(bytes))!=-1){
           out.write(bytes,0,len);
            out.flush();

        }
        ss.close();


    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值