发送一个文件夹给服务器,并且接收服务器返回的指令

//客户端

public class TcpClient {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket("192.168.38.22",2365);

        OutputStream os = s.getOutputStream();
        DataOutputStream dos  =new DataOutputStream(os);
        File file = new File("E:/JAVA8/22B9A1D9.gif");
        dos.writeUTF(file.getName());
        BufferedOutputStream bos = new BufferedOutputStream(os);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));


        byte[] b = new byte[1024];
        int len;
        while ((len = bis.read(b))!=-1) {
            bos.write(b, 0, len);
        }
        s.shutdownOutput();//关闭输出,如果没有此指令,客户端和服务器会互相等待

        //接收回复的数据
        System.out.println("服务器回复:");
        InputStream is = s.getInputStream();
        byte[] bytes = new byte[1024];
        int read = is.read(bytes);
        System.out.println(new String(bytes,0,read));

//      bos.close();  /关闭输出指令之后不再需要此关闭流的方法
        bis.close();
        s.close();

    }
}

服务器端

public class TcpServer {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(2365);
        while (true) {
            Socket s = ss.accept();

            InputStream is = s.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            String s1 = dis.readUTF();

            if (s1.endsWith(".exe")){
                System.out.println("格式有误上传失败");
                continue;
            }
            String ip = s.getInetAddress().getHostAddress();
            System.out.println(ip+"正在上传"+s1);
            BufferedInputStream bis = new BufferedInputStream(is);

            BufferedOutputStream bos = new BufferedOutputStream(new
            FileOutputStream("E:/JAVA8/" + System.currentTimeMillis() + s1));

            byte[] b = new byte[1024];
            int len;
            while ((len =bis.read(b))!=-1) {
                bos.write(b, 0, len);
                System.out.println("标记位...");
            }
            System.out.println("上传成功");

            //回复给客户端
            OutputStream os = s.getOutputStream();
            os.write("上传成功".getBytes());

            bos.close();
            bis.close();
            s.close();
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值