关于java:java网络编程TCPUDP笔记

客户端
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();//我曾经传输完了
        //确认服务器接管实现,[WebMoney下载](https://www.gendan5.com/wallet/WebMoney.html)能力断开连接
        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) {

            }
        }
    }
}

}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理