Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3648394
  • 博文数量: 365
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2522
  • 用 户 组: 普通用户
  • 注册时间: 2019-10-28 13:40
文章分类

全部博文(365)

文章存档

2023年(8)

2022年(130)

2021年(155)

2020年(50)

2019年(22)

我的朋友

分类: Java

2021-05-14 16:22:14

客户端

package com.ZXF.Net;

import java.io.*;

import java.net.InetAddress;

import java.net.Socket;

public class TcpClientDemo1 {

    public static void main(String[] args) {

        Socket socket=null;

        OutputStream os=null;

        FileInputStream fis=null;

        InputStream is=null;

        ByteArrayOutputStream baos=null;

        try {

            //1.创建一个socket连接

            socket=new Socket(InetAddress.getByName("127.0.0.1"),9000);

            //2.创建一个输出流

             os=socket.getOutputStream();

             //3.读取文件

             fis=new FileInputStream(new File("林允儿.jpg"));

             //4.写出文件

            byte[] buffer=new byte[1024];

            int len=-1;

            while ((len=fis.read(buffer))!=-1){

                os.write(buffer,0,len);

            }

            //通知服务端,我已结束

            socket.shutdownOutput();//我已经传输完了

            //确认服务器接收完成,货币代码才能断开连接

            is=socket.getInputStream();

            //由于服务发过来的确认信息是字符数组,所以创建数组管道流

            baos=new ByteArrayOutputStream();

            byte[] buffer2=new byte[2014];

            int len2=-1;

            while ((len2=is.read(buffer2))!=-1){

                baos.write(buffer2,0,len2);

            }

            System.out.println(baos.toString());

        } catch (IOException e) {

            e.printStackTrace();

        }

        finally {

            //关闭资源,先开后关

            if (baos!=null){

                try {

                    baos.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (is!=null){

                try {

                    is.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (fis!=null){

                try {

                    fis.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (os!=null){

                try {

                    fis.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (socket!=null){

                try {

                    fis.close();

                } catch (IOException e) {

 

                }

            }

        }

    }

}

 

阅读(1192) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~