第14章:网络编程

14.1 网络编程概述

14.1.1 网络编程概述

       1)Java是Internet上的语言,它从语言级上提供了对网络应用程序的支持,程序员能够很容易开发常见的网络应用程                            序。

       2)Java提供的网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在Java的本机安装系统里,由JVM进行                              控制,并且Java实现了一个跨平台的网络库,程序员面对的是一个统一的网络编程环境。

14.1.2 网络基础

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

       2)网络编程的目的:直接或间接地通过网络协议与其它计算机进行通讯。

       3)网络编程中两个主要的问题:

              a)如何准确地定位网络上一台或多台主机

              b)找到主机后如何高效地进行数据传输

       4)如何实现网络中的主机互相通信:

              a)通信双方地址

              b)一定的规则(有两套参考模型)

                     >OSI参考模型:模型过于理想化,未能在因特网上进行广泛推广

                     >TCP/IP参考模型(或TCP/IP协议):事实上的国际标准

                         第14章:网络编程

第14章:网络编程

14.2 通讯要素

14.2.1 通讯要素一:IP和端口号

       1)IP地址:InetAddress

              a)唯一的标识Internet上的计算机

              b)本地回环地址(hostAddress):127.0.0.1 主机名(hostName):localhost

              c)不易记忆

       2)端口号标识正在计算机上运行的进程(程序)

              a)不同的进程有不同的端口号

              b)被规定为一个16位的整数0~65535.其中,0~1023被预先定义的服务通信占用(如MySql占用端口3306,http                                   占用端口80等)。除非我们需要访问这些特定服务,否则,就应该使用1024~65535这些端口中的某一个进行                                 通信,以免发生端口冲突。

              c)端口号与IP地址的组合得出一个网络套接字

14.2.2 通讯要素二:网络通信协议

    1)网络通信协议

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

    2)通信协议分层的思想

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

    3TCP/IP协议簇

       a)传输控制协议TCPTransmission Control Protocol

       b)用户数据协议UDPUser Datagram Protocol

4TCP/IP以其两个主要协议:传输控制协议(TCP)和网络互联协议(IP)而得名,实际上是一组协议,包括多个具有                    不同功能且互为关联的协议

5IPInternet Protocol)协议是网络层的主要协议,支持网间互连的数据通信。

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

14.3 InetAddress类

14.3.1 InetAddress位于java.net包下

       1InetAddress用来代表IP地址。一个InetAdress的对象就代表着一个IP地址

       2)如何创建InetAddress的对象:getByName(String host)

       3getHostName(): 获取IP地址对应的域名

             getHostAddress():获取IP地址

public class TestInetAddress {
public static void main(String[] args) throws Exception {
//创建一个InetAddress对象:getByName()
InetAddress inet1 = InetAddress.getByName("www.baidu.com");
    //inet1 = InetAddress.getByName("42.121.6.2");
    System.out.println(inet1);
    //两个方法
    System.out.println(inet1.getHostName());
    System.out.println(inet1.getHostAddress());
    //获取本机的IP:getLocalHost()
    InetAddress inet2 = InetAddress.getLocalHost();
    }
}

14.4 TCP网络通信

14.4.1 TCP协议

    1)使用TCP协议前,须先建立TCP连接,形成传输数据通道

    2)传输前,采用“三次握手”方式,是可靠的

    3TCP协议进行通信的两个应用进程:客户端、服务端

    4)在连接中可进行大数据量的传输

    5)传输完毕,需要释放已建立的连接,效率低

14.4.2 Socket

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

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

   3)网络通信其实就是Socket间的通信

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

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

14.4.3 TCP编程一

 public class TestTCP1 {
    // 客户端
    @Test
    public void client() {
       Socket socket = null;
       OutputStream os = null;
       try {
           // 1.创建一个Socket的对象,通过构造器指明服务端的IP地址,以及其接收程序的端口号
           socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
           // 2.getOutputStream():发送数据,方法返回OutputStream的对象
           os = socket.getOutputStream();
           // 3.具体的输出过程
           os.write("我是客户端,请多关照".getBytes());
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           // 4.关闭相应的流和Socket对象
           if (os != null) {
              try {
                  os.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }

           }
           if (socket != null) {
              try {
                  socket.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
           }
       }
    }
    // 服务端
    @Test
    public void server() {
       ServerSocket ss = null;
       Socket s = null;
       InputStream is = null;
       try {
           // 1.创建一个ServerSocket的对象,通过构造器指明自身的端口号
           ss = new ServerSocket(9090);
           // 2.调用其accept()方法,返回一个Socket的对象
           s = ss.accept();
           // 3.调用Socket对象的getInputStream()获取一个从客户端发送过来的输入流
           is = s.getInputStream();
           // 4.对获取的输入流进行的操作
           byte[] b = new byte[20];
           int len;
           while ((len = is.read(b)) != -1) {
              String str = new String(b, 0, len);
              System.out.print(str);
           }
            System.out.println("收到来自于" + s.getInetAddress().getHostAddress()
                  + "的连接");
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           // 5.关闭相应的流以及Socket、ServerSocket的对象
           if (is != null) {
              try {
                  is.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }

           }
           if (s != null) {
              try {
                  s.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
           }
           if (ss != null) {
              try {
                  ss.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
           }
       }
    }
}

  

14.4.4 TCP编程二



 
public class TestTCP2 {
    //客户端
    @Test
    public void client(){
       Socket socket = null;
       OutputStream os = null;
       InputStream is = null;
       try {
           socket = new Socket(InetAddress.getByName("127.0.0.1"),8989);
           os = socket.getOutputStream();
           os.write("我是客户端".getBytes());
           //shutdownOutput():执行此方法,显式的告诉服务端发送完毕!
           socket.shutdownOutput();
           is = socket.getInputStream();
           byte[] b = new byte[20];
           int len;
           while((len = is.read(b)) != -1){
              String str = new String(b,0,len);
              System.out.print(str);
           }
       } catch (IOException e) {
           e.printStackTrace();
       }finally{
           if(is != null){
              try {
                  is.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
           }
           if(os != null){
              try {
                  os.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
           }
           if(socket != null){
              try {
                  socket.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
           }
       }
    }
    //服务端
    @Test
    public void server(){
       ServerSocket ss = null;
       Socket s = null;
       InputStream is = null;
       OutputStream os = null;
       try {
           ss = new ServerSocket(8989);
           s = ss.accept();
           is = s.getInputStream();
           byte[] b = new byte[20];
           int len;
           while((len = is.read(b)) != -1){
              String str = new String(b,0,len);
              System.out.print(str);
           }
           os = s.getOutputStream();
           os.write("我已收到你的情意".getBytes());
       } catch (IOException e) {
           e.printStackTrace();
       }finally{
           if(os != null){
              try {
                  os.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
           }
           if(is != null){
              try {
                  is.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
           }
           if(s != null){
              try {
                  s.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
              
           }
           if(ss != null){
              try {
                  ss.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }   
           }
       }   
    }
}

14.4.5 TCP编程三     


  public class TestTCP3 {
    @Test
    public void client()throws Exception{
       //1.创建Socket的对象
       Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9898);
       //2.从本地获取一个文件发送给服务端
       OutputStream os = socket.getOutputStream();
       FileInputStream fis = new FileInputStream(new File("1.jpg"));
       byte[] b = new byte[1024];
       int len;
       while((len = fis.read(b)) != -1){
           os.write(b,0,len);
       }
       socket.shutdownOutput();
       //3.接收来自于服务端的信息
       InputStream is = socket.getInputStream();
       byte[] b1 = new byte[1024];
       int len1;
       while((len1 = is.read(b1)) != -1){
           String str = new String(b1,0,len1);
           System.out.print(str);
       }
       //4.关闭相应的流和Socket对象
       is.close();
       os.close();
       fis.close();
       socket.close();
    }
    @Test
    public void server() throws Exception{
       //1.创建一个ServerSocket的对象
       ServerSocket ss = new ServerSocket(9898);
       //2.调用其accept()方法,返回一个Socket的对象
       Socket s = ss.accept();
       //3.将从客户端发送来的信息保存到本地
       InputStream is = s.getInputStream();
       FileOutputStream fos = new FileOutputStream(new File("3.jpg"));
       byte[] b = new byte[1024];
       int len;
       while((len = is.read(b)) != -1){
           fos.write(b, 0, len);
       }
       System.out.println("收到来自于" + s.getInetAddress().getHostAddress() + "的文
       件");
       //4.发送"接收成功"的信息反馈给客户端
       OutputStream os = s.getOutputStream();
       os.write("你发送的图片我已接收成功!".getBytes());
       //5.关闭相应的流和Socket及ServerSocket的对象
       os.close();
       fos.close();
       is.close();
       s.close();
       ss.close();
    }
}

14.5 UDP通信

14.5.1 UDP协议

    1)将数据、源、目的封装成数据包,不需要建立连接

    2)每个数据报的大小限制在64K

    3)因无需连接,故是不可靠的

    4)发送数据结束时无需释放资源,速度快

14.5.2 UDP网络通信

    1)类DatagramSocketDatagramPacket实现了基于UDP协议网络程序

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

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

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

    5)流程

       a)DatagramSocket与DatagramPacket

       b)建立发送端,接收端

       c)建立数据包

       d)调用Socket的发送、接收方法

       e)关闭Socket


public class TestUDP {
    // 发送端
    @Test
    public void send() {
       DatagramSocket ds = null;
       try {
           ds = new DatagramSocket();
           byte[] b = "你好,我是要发送的数据".getBytes();
           //创建一个数据报:每一个数据报不能大于64k,都记录着数据信息,发送端的IP、端口号,以
             及要发送到
           //的接收端的IP、端口号。
           DatagramPacket pack = new DatagramPacket(b, 0, b.length,
           InetAddress.getByName("127.0.0.1"), 9090);
           ds.send(pack);
       }catch (IOException e) {
           e.printStackTrace();
       }finally{
           if(ds != null){
              ds.close();
           }
       }
    }
    // 接收端
    @Test
    public void rceive() {
       DatagramSocket ds = null;
       try {
           ds = new DatagramSocket(9090);
           byte[] b = new byte[1024];
           DatagramPacket pack = new DatagramPacket(b, 0, b.length);
           ds.receive(pack);
           String str = new String(pack.getData(), 0, pack.getLength());
           System.out.println(str);
       }catch (IOException e) {
           e.printStackTrace();
       }finally{
           if(ds != null){
              ds.close();
           }
       }
    }
}

    6)发送端与接收端是两个独立的运行程序

14.6URL编程 

14.6.1 URL编程

       1)URL(Uniform Resource Locator):统一资源定位符,它表示Internet上某一资源的地址。通过URL我们可以访                             问Internet上的各种网络资源,比如最常见的www,ftp站点。浏览器通过解析给定的URL可以在网络上查找相应的                           文件或其他资源

       2)URL的基本结构由五部分组成:

              a)<传输协议>://<主机名>:<端口号>/<文件名>

              b)例如:http://192.168.1.100:8080/helloworld/index.jsp

       3)类URL的构造方法都声明抛出非运行时异常,必须要对这一异常进行处理,通常是用try-catch语句进行捕获

       4)一个URL对象生成后,其属性是不能被改变的,但可以通过它给定的方法来获取这些属性:

              apublic String getProtocol(  )    获取该URL的协议名

              bpublic String getHost(  )         获取该URL的主机名

              cpublic String getPort(  )         获取该URL的端口号

              dpublic String getPath(  )         获取该URL的文件路径

              epublic String getFile(  )         获取该URL的文件名

               fpublic String getRef(  )          获取该URL在文件中的相对位置

              gpublic String getQuery(   )       获取该URL的查询名

14.6.2 针对HTTP协议的URLConnection

    1URL的方法openStream():能从网络上读取数据

    2)若希望输出数据,例如向服务器端的CGI(公共网关接口-Common Gateway Interface-的简称,是用户浏览器和服                          务器端的应用程序进行连接的接口)程序发送一些数据,则必须先与URL建立连接,然后才能对其进行读写,此时                        需要使用URLConnection

    3URLConnection:表示到URL所引用的远程对象的连接。当与一个URL建立连接时,首先要在一个URL对象上通过                        方法openConnect()生成对应的URLConnection对象。如果连接过程失败,将产生IOException

    aURL netchinaren = new URL(“http://www.atguigu.com/index.shtml”);

    b)URL Connectonn u = netchinaren.openConnection();

    4)通过URLConnection对象获取的输入流和输出流,即可以与现有的CGI程序进行交互

    第14章:网络编程


public class TestURL {
    public static void main(String[] args) throws Exception {
       URL url = new URL("http://127.0.0.1:8080/examples/HelloWorld.txt?a=b");//File file = new File("文件的路径");
       //如何将服务端的资源读取进来:openStream()
       InputStream is2 = url.openStream();
       byte[] b2 = new byte[20];
       int len2;
       while((len2 = is2.read(b2)) != -1){
           String str = new String(b2,0,len2);
           System.out.print(str);
       }
       is2.close();
       //如果既有数据的输入,又有数据的输出,则考虑使用URLConnection
       URLConnection urlConn = url.openConnection();
       InputStream is1 = urlConn.getInputStream();
       FileOutputStream fos = new FileOutputStream(new File("abc.txt"));
       byte[] b1 = new byte[20];
       int len1;
       while((len1 = is1.read(b1)) != -1){
           fos.write(b1, 0, len1);
       }
       fos.close();
       is1.close();
    }
}