[JavaSE]第十三章 网络编程

13.1 网络编程概述

  • 计算机网络:把分布在不同地理区域的计算机与专门的外部设备用通信线路互连成一个规模大、功能强的网络系统,从而使众多的计算机可以方便地互相传递信息、共享硬件、软件、数据信息等资源

  • 网络编程的目的:直接或间接地通过网络协议与其它计算机实现数据交换,进行通讯

  • 网络编程中有两个主要的问题:

    • 如何准确地定位网络上一台或多台主机;定位主机上的特定的应用

    • 找到主机后如何可靠高效地进行数据传输

13.2 网络通信要素概述

  • 如何实现网络中的主机互相通信

    • 通信双方地址

      • IP
      • 端口号
    • 网络通信协议

      • OSI参考模型:模型过于理想化,未能在因特网上进行广泛推广
      • TCP/IP参考模型(或TCP/IP协议):事实上的国际标准
      TCP/IP 参考模型TCP/IP 参考模型各层对应协议
      应用层HTTP、FTP、Telnet、DNS…
      传输层TCP、UDP、…
      网络层IP、ICMP、ARP…
      物理+数据链路层Link

13.3 IP和端口号

  • IP 地址:InetAddress

    • 唯一的标识 Internet 上的计算机(通信实体)
  • 端口号:标识正在计算机上运行的进程(程序)

  • 端口号与 IP 地址的组合得出一个网络套接字:Socket

  • Internet 上的主机有两种方式表示地址:

    • 域名(hostName):www.shiyiri.top
    • IP 地址(hostAddress):185.199.109.153
  • InetAddress 类没有提供公共的构造器,而是提供了如下几个静态方法来获取 InetAddress 实例:

    • public static InetAddress getLocalHost()
    • public static InetAddress getByName(String host)
  • InetAddress 提供了如下几个常用的方法:

    • public String getHostAddress()**:**返回 IP 地址字符串(以文本表现形式)
    • public String getHostName():获取此 IP 地址的主机名
    • public boolean isReachable(int timeout):测试是否可以达到该地址
public static void main(String[] args) {

        try {
            InetAddress inet1 = InetAddress.getByName("192.168.48.1");
            System.out.println(inet1);

            InetAddress address = InetAddress.getByName("www.mi.com");
            System.out.println(address);

            //获取本地IP
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println(localHost);

            //getHostName()
            String hostName = InetAddress.getByName("185.199.109.153").getHostName();
            System.out.println(hostName);

            String hostAddress = InetAddress.getByName("www.shiyiri.top").getHostAddress();
            System.out.println(hostAddress);

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

13.4 网络协议

  • 网络通信协议:计算机网络中实现通信必须有一些约定,即通信协议,对速率、传输代码、代码结构、传输控制步骤、出错控制等制定标准。

  • 通信协议分层的思想:在制定协议时,把复杂成份分解成一些简单的成份,再将它们复合起来。最常用的复合方式是层次方式,即同层间可以通信、上一层可以调用下一层,而与再下一层不发生关系。各层互不影响,利于系统的开发和扩展

  • 传输层协议中有两个非常重要的协议:

    • 传输控制协议 TCP(Transmission Control Protocol)
    • 用户数据报协议 UDP(User Datagram Protocol)
  • TCP/IP **以其两个主要协议:传输控制协议(TCP)和网络互联协议(IP)**而得名,实际上是一组协议,包括多个具有不同功能且互为关联的协议

  • IP(Internet Protocol) 协议是网络层的主要协议,支持网间互连的数据通信

  • TCP/IP协议模型从更实用的角度出发,形成了高效的四层体系结构,即物理链路层网络层传输层应用层

13.4.1 TCP 协议

  • 使用 TCP 协议前,须先建立 TCP 连接,形成传输数据通道
  • 传输前,采用“三次握手”方式,点对点通信,是可靠的
  • TCP协议进行通信的两个应用进程:客户端、服务端
  • 在连接中可进行大数据量的传输
  • 传输完毕,需释放已建立的连接,效率低

13.4.2 UDP 协议

  • 将数据、源、目的封装成数据包,不需要建立连接
  • 每个数据包的大小限制在 64K 内
  • 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的
  • 可以广播发送
  • 发送数据结束时无需释放资源,开销小,速度快

13.4.3 Socket

  • 利用套接字(Socket)开发网络应用程序早已被广泛的采用,以至于成为事实上的标准

  • 网络上具有唯一标识的 IP 地址和端口号组合在一起才能构成唯一能识别的标识符套接字

  • 通信的两端都要有 Socket,是两台机器间通信的端点

  • 网络通信其实就是 Socket 间的通信

  • Socket 允许程序把网络连接当成一个流,数据在两个 Socket 间通过 IO 传输

  • 一般主动发起通信的应用程序属客户端,等待通信请求的为服务端

  • Socket 分类:

    • 流套接字(stream socket):使用 TCP 提供可依赖的字节流服务
    • 数据包套接字(datagram socket):使用 UDP 提供“尽力而为”的数据报服务
  • Socket 类的常用构造器

    • public Socket(InetAddress address,int port):创建一个流套接字并将其连接到指定 IP 地址的指定端口号
    • public Socket(String host,int port):创建一个流套接字并将其连接到指定主机上的指定端口号
  • Socket 类的常用方法

    • public InputStream getInputStream():返回此套接字的输入流。可以用于接收网络消息
    • public OutputStream getOutputStream():返回此套接字的输出流。可以用于发送网络消息
    • public InetAddress getInetAddress():此套接字连接到的远程 IP 地址;如果套接字是未连接的,则返回 null
    • public InetAddress getLocalAddress():获取套接字绑定的本地地址。 即本端的 IP 地址
    • public int getPort():此套接字连接到的远程端口号;如果尚未连接套接字,则返回 0
    • public int getLocalPort():返回此套接字绑定到的本地端口。 如果尚未绑定套接字,则返回 -1。即本端的端口号
    • public void close():关闭此套接字。套接字被关闭后,便不可在以后的网络连接中使用(即无法重新连接或重新绑定)。需要创建新的套接字对象。 关闭此套接字也将会关闭该套接字的 InputStream 和 OutputStream。
    • public void shutdownInput():如果在套接字上调用 shutdownInput() 后从套接字输入流读取内容,则流将返回 EOF(文件结束符)。 即不能在从此套接字的输入流中接收任何数据
    • public void shutdownOutput():禁用此套接字的输出流。对于 TCP 套接字,任何以前写入的数据都将被发送,并且后跟 TCP 的正常连接终止序列。 如果在套接字上调用 shutdownOutput() 后写入套接字输流,则该流将抛出 IOException。 即不能通过此套接字的输出流发送任何数据

13.5 TCP 网络编程

  • 客户端 Socket 的工作过程包含以下四个基本的步骤

    • 创建 Socket:根据指定服务端的 IP 地址或端口号构造 Socket 类对象。若服务器端响应,则建立客户端到服务器的通信线路。若连接失败,会出现异常
    • 打开连接到 Socket 的输入/出流: 使用 getInputStream() 方法获得输入流,使用getOutputStream()方法获得输出流,进行数据传输
    • 按照一定的协议对 Socket 进行读/写操作:通过输入流读取服务器放入线路的信息(但不能读取自己放入线路的信息),通过输出流将信息写入线程
    • 关闭 Socket:断开客户端到服务器的连接,释放线路
    @Test
        public void client() {
            Socket socket = null;
            OutputStream os = null;
            try {
                //1.创建 Socket 对象,指明服务器端的IP和端口号
                InetAddress inet = InetAddress.getByName("127.0.0.1");
                socket = new Socket(inet, 8989);
                //2.获取一个输出流,用于输出数据
                os = socket.getOutputStream();
                //3.写出数据的操作
                os.write("你好,我是客户端".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //4.关闭资源
                try {
                    assert os != null;
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    
  • 服务器程序的工作过程包含以下四个基本的步骤

    • 调用 ServerSocket(int port):创建一个服务器端套接字,并绑定到指定端口上。用于监听客户端的请求
    • 调用 accept():监听连接请求,如果客户端请求连接,则接受连接,返回通信套接字对象
    • 调用该 Socket 类对象的 getOutputStream() getInputStream ():获取输出流和输入流,开始网络数据的发送和接收
    • 关闭 ServerSocketSocket 对象:客户端访问结束,关闭通信套接字
        @Test
        public void server() {
            Socket accept = null;
            InputStream is = null;
            ByteArrayOutputStream baos = null;
            try {
                //1.创建服务器端的ServerSocket,指明字节的端口号
                ServerSocket socket = new ServerSocket(8989);
                //2.调用 accept() 表示接收来自客户端的socket
                accept = socket.accept();
                //3.获取输入流
                is = accept.getInputStream();
    
                //不建议这样写,可能会有乱码
    /*            byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    String str = new String(buffer, 0, len);
                    System.out.println(str);
                }*/
                //4.读取流中的数据
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[5];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                System.out.println(baos.toString());
                System.out.println("收到了来自于:" + socket.getInetAddress().getHostName() + "的信息");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //5.释放资源
                try {
                    assert baos != null;
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
  • 客户端发送文件给服务端,服务端将文件保存在本地

    @Test
        public void client() {
            Socket socket = null;
            OutputStream os = null;
            BufferedInputStream bis = null;
            try {
                socket = new Socket(InetAddress.getByName("localhost"), 9000);
                os = socket.getOutputStream();
    
                bis = new BufferedInputStream(new FileInputStream("../data/photo/q.png"));
    
                byte[] buffer = new byte[1024];
                int len;
                while ((len = bis.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    assert bis != null;
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
    
        }
    
        @Test
        public void server() {
    
            ServerSocket socket = null;
            Socket accept = null;
            InputStream is = null;
            BufferedOutputStream bos = null;
            try {
                socket = new ServerSocket(9000);
                accept = socket.accept();
    
                is = accept.getInputStream();
    
                bos = new BufferedOutputStream(new FileOutputStream("photo1.png"));
    
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    assert bos != null;
                    bos.close();
                    is.close();
                    accept.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
  • 从客户端发送文件给服务端,服务端保存在本地,并返回“发送成功”给客户端。并关闭相应的连接

    	@Test
        public void client() {
            Socket socket = null;
            OutputStream os = null;
            BufferedInputStream bis = null;
            ByteArrayOutputStream baos = null;
            try {
                socket = new Socket(InetAddress.getByName("localhost"), 9010);
                os = socket.getOutputStream();
    
                bis = new BufferedInputStream(new FileInputStream("../data/photo/q.png"));
    
                //客户端发送文件
                byte[] buffer = new byte[1024];
                int len;
                while ((len = bis.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
                //关闭数据输出
                socket.shutdownOutput();
    
                //客户端接收服务器端信息
                byte[] buffer2 = new byte[1024];
                int len1;
                InputStream is = socket.getInputStream();
                baos = new ByteArrayOutputStream();
                while ((len1 = is.read(buffer2)) != -1) {
                    baos.write(buffer2, 0, len1);
                }
                System.out.println(baos.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    assert baos != null;
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        @Test
        public void server() {
    
            ServerSocket socket = null;
            Socket accept = null;
            InputStream is = null;
            BufferedOutputStream bos = null;
            try {
                socket = new ServerSocket(9010);
                accept = socket.accept();
    
                is = accept.getInputStream();
    
                bos = new BufferedOutputStream(new FileOutputStream("photo2.png"));
    
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
    
                //服务器端给予客户端反馈
                OutputStream outputStream = accept.getOutputStream();
                outputStream.write("你好,照片已收到".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    assert bos != null;
                    bos.close();
                    is.close();
                    accept.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    

13.6 UDP 网络编程

  • DatagramSocketDatagramPacket 实现了基于 UDP 协议网络程序

  • UDP 数据报通过数据包套接字 DatagramSocket 发送和接收,系统不保证 UDP 数据报一定能够安全送到目的地,也不能确定什么时候可以抵达

  • DatagramPacket 对象封装了 UDP 数据报,在数据报中包含了发送端的 IP 地址和端口号以及接收端的 IP 地址和端口号

  • UDP 协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和接收方的连接

  • DatagramSocket 类的常用方法

    • public DatagramSocket(int port):创建数据报套接字并将其绑定到本地主机上的指定端口。套接字将被绑定到通配符地址,IP 地址由内核来选择
    • public DatagramSocket(int port,InetAddress laddr):创建数据报套接字,将其绑定到指定的本地地址。本地端口必须在 0 到 65535 之间(包括两者)。如果 IP 地址为 0.0.0.0,套接字将被绑定到通配符地址,IP 地址由内核选择
    • public void close():关闭此数据报套接字
    • public void send(DatagramPacket p):从此套接字发送数据报包。DatagramPacket 包含的信息指示:将要发送的数据、其长度、远程主机的 IP 地址和远程主机的端口号
    • public void receive(DatagramPacket p):从此套接字接收数据报包。当此方法返回时,DatagramPacket 的缓冲区填充了接收的数据。数据报包也包含发送方的 IP 地址和发送方机器上的端口号。 此方法在接收到数据报前一直阻塞。数据报包对象的 length 字段包含所接收信息的长度。如果信息比包的长度长,该信息将被截短
    • public InetAddress getLocalAddress():获取套接字绑定的本地地址。
    • public int getLocalPort():返回此套接字绑定的本地主机上的端口号。
    • public InetAddress getInetAddress():返回此套接字连接的地址。如果套接字未连接,则返回 null
    • public int getPort():返回此套接字的端口。如果套接字未连接,则返回 -1
  • DatagramPacket 类的常用方法

    • public DatagramPacket(byte[] buf,int length):构造 DatagramPacket,用来接收长度为 length 的数据包。length 参数必须小于等于 buf.length
    • public DatagramPacket(byte[] buf,int length,InetAddress address,int port):构造数据报包,用来将长度为 length 的包发送到指定主机上的指定端口号。length 参数必须小于等于 buf.length
    • public InetAddress getAddress():返回某台机器的 IP 地址,此数据报将要发往该机器或者是从该机器接收到的
    • public int getPort():返回某台远程主机的端口号,此数据报将要发往该主机或者是从该主机接收到的
    • public byte[] getData():返回数据缓冲区。接收到的或将要发送的数据从缓冲区中的偏移量 offset 处开始,持续 length 长度
    • public int getLength():返回将要发送或接收到的数据的长度
  • 流程

    • DatagramSocket 与 DatagramPacket
    • 建立发送端,接收端
    • 建立数据包
    • 调用 Socket 的发送、接收方法
    • 关闭 Socket
	//发送端
    @Test
    public void sender() {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();

            byte[] data = "UDP发送信息的方式".getBytes();

            InetAddress localHost = InetAddress.getLocalHost();
            DatagramPacket packet = new DatagramPacket(data, 0, data.length, localHost, 9020);

            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            assert socket != null;
            socket.close();
        }
    }

    //接收端
    @Test
    public void receiver() {

        DatagramSocket socket = null;
        DatagramPacket packet = null;
        try {
            socket = new DatagramSocket(9020);
            byte[] buffer = new byte[1024];
            packet = new DatagramPacket(buffer, 0, buffer.length);

            socket.receive(packet);

            System.out.println(new String(packet.getData(), 0, packet.getLength()));

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            assert socket != null;
            socket.close();
        }
    }

13.7 URL 编程

  • URL(Uniform Resource Locator):统一资源定位符,它表示 Internet 上某一资源的地址

  • URL 的基本结构由 5 部分组成:<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表

  • URL 构造器

    • public URL (String spec):通过一个表示 URL 地址的字符串可以构造一个 URL 对象
      • URL url = new URL ("http://www.shiyiri.top/node/102.html")
    • public URL(URL context, String spec):通过基 URL 和相对 URL 构造一个 URL 对象
      • URL downloadUrl = new URL(url, "download.html")
    • public URL(String protocol, String host, String file)
      • URL downloadUrl = new URL("https","www.shiyiri.top", “download.html")
    • public URL(String protocol, String host, int port, String file)
      • URL url = new URL("https", "www.shiyiri.top", 80, “download.html")
  • URL 类的构造器都声明抛出非运行时异常,必须要对这一异常进行处理,通常是用 try-catch 语句进行捕获

  • URL 常用方法:

    • public String getProtocol():获取该 URL 的协议名
    • public String getHost():获取该 URL 的主机名
    • public String getPort():获取该 URL 的端口号
    • public String getPath():获取该 URL 的文件路径
    • public String getFile():获取该 URL 的文件名
    • public String getQuery():获取该 URL 的查询名
    public static void main(String[] args) {
    
            try {
                URL url = new URL("http://localhost:8080/examples/hello.txt?name=Tom&password=123");
    
                //public String getProtocol( ) 获取该URL的协议名
                System.out.println(url.getProtocol());
    
                //public String getHost( ) 获取该URL的主机名
                System.out.println(url.getHost());
    
                //public String getPort( ) 获取该URL的端口号
                System.out.println(url.getPort());
    
                //public String getPath( ) 获取该URL的文件路径
                System.out.println(url.getPath());
    
                //public String getFile( ) 获取该URL的文件名
                System.out.println(url.getFile());
    
                //public String getQuery( ) 获取该URL的查询名
                System.out.println(url.getQuery());
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    
public static void main(String[] args) {
    HttpURLConnection urlConnection = null;
    InputStream is = null;
    BufferedOutputStream bos = null;
    try {
        URL url = new URL("https://www.cnblogs.com/webgo/p/15785157.html");

        urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.connect();

        is = urlConnection.getInputStream();
        bos = new BufferedOutputStream(new FileOutputStream("data/hello.txt"));

        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        try {
            assert bos != null;
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值