JAVASE网络编程之TCP实现传输文件

客户端发送文件,服务端接收后作出响应

public class TCPClientDome02 {

    public static void main(String[] args) {
        //设置地址
        try {
            InetAddress name = InetAddress.getByName("127.0.0.1");

            Socket socket = new Socket(name, 9999);

            //创建一个输出流
            OutputStream os = socket.getOutputStream();
            //3.读取文件
            FileInputStream fis = new FileInputStream(new File("图片.jpg"));

            byte[] buffer = new byte[1024];

            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }

            //通知服务器我已经结束了

            socket.shutdownOutput();

            //确认服务器接收完毕,才能够断开连接
            InputStream is = socket.getInputStream();

            ByteOutputStream boas = new ByteOutputStream();

            byte[] byte2 =new byte[1024];

            int len2;

            while ((len2 =is.read(byte2))!=-1){
                boas.write(byte2);
            }

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


            //关闭资源

            fis.close();
            os.close();
            socket.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

服务端接收数据,并对客户端做出响应

public class TCPServerDome02 {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            // 2等待客户端连接过来
            Socket accept = serverSocket.accept();
            //获取输入流
            InputStream is = accept.getInputStream();

            //文件输出
            FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));

            int len;
            byte[] buffer = new byte[1024];

            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }

            //通知客户端我已经接收完毕了
            OutputStream os = accept.getOutputStream();
            os.write("我接收完毕了,你可以关闭了".getBytes());


            fos.close();
            is.close();
            accept.close();
            serverSocket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值