11-Java的网络编程

1、网络编程概述

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

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

  • 计算机网络

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

    • 直接或间接地通过网络协议与其它计算机实现数据交换,进行通讯。
  • 网络编程中有两个主要的问题

    • 问题一:如何准确地定位网络上一台或多台主机;定位主机上的特定的应用
    • 问题二:找到主机后如何可靠高效地进行数据传输

2、网络通信要素

网络编程中的两个要素

  1. 对应问题一: IP和端口号
  2. 对应问题二: 提供网络通信协议: TCP/IP参数模型(应用层、传输层、网络层、物理+数据链路层)

网络通信协议

在这里插入图片描述

通讯过程

在这里插入图片描述

3、通讯要素一: IP和端口号

3.1、Ip的理解

  • IP:唯一的标识 Internet 上的计算机(通信实体)

  • 在Java中使用InetAddress类代表IP

  • IP分类:IPv4 和 IPv6 ; 万维网 和 局域网

  • 域名: 通过域名解析服务器将域名解析为IP地址 www.baidu.com www.mi.com www.jd.com

  • 域名解析:域名容易记忆,当在连接网络时输入一个主机的域名后,域名服务器(DNS)负责将域名转化成IP地址,这样才能和主机建立连接。

  • 本地回路地址:127.0.0.1 对应着:localhost

3.2、InetAddress类

此类的一个对象就代表着一个具体的IP地址

实例化InetAddress

getByName(String host);//解析获取ip(域名)地址

getLocalHost();//获得本地ip地址

public class InetAddressTest {
    public static void main(String[] args) {
        try {
            InetAddress localHost = InetAddress.getByName("www.vip.com");
            System.out.println(localHost);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

常用方法

getHostName();//获取域名

getHostAddress();//获取ip地址

public class InetAddressTest {
    public static void main(String[] args) {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println(localHost.getHostAddress());
            System.out.println(localHost.getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

3.3、端口号

用于标识正在计算机上运行的进程。

  • 要求:不同的进程不同的端口号
  • 范围:被规定为一个 16 位的整数 0~65535。
  • 分类:
    • 公认端口:0~1023.被预先定义的服务通信占用(如:HTTP占用端口80,FTP占用端口21,TeInet占用端口23)。
    • 注册端口:1024~49151.分配给用户进程或应用程序。(如:Tomcat占用端口8080,MSQL占用端口3306,Oracle占用端口1521等)。
    • 动态私有端口:49152~65535。

4、通讯要素二: 网络协议

4.1、分层模型

在这里插入图片描述

4.2、TCP和UDP的区别

TCP协议

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

UDP协议:

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

4.3、TCP三次握手和四次挥手

在这里插入图片描述

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-G5G8Un5X-1604929128275)(11-网络编程.assets/image-20201109131501269.png)]

5、套接字Socket

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

  • 利用套接字(Socket)开发网络应用程序早已被广泛的采用,以至于成为事实上的标准。
  • 网络上具有唯一标识的P地址和端口号组合在一起才能构成唯一能识别的标识符套接字。
  • 通信的两端都要有 Socket,是两台机器间通信的端点。
  • 网络通信其实就是 Socket间的通信
  • Socket允许程序把网络连接当成一个流,数据在两个Socket间通过IO传输。
  • 一般主动发起通信的应用程序属客户端,等待通信请求的为服务端
  • Socket分类
    • 流套接字(stream socket):使用TCP提供可依赖的字节流服务
    • 数据报套接字(datagram socket):使用UDP提供“尽力而为”的数据报服务[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传在这里插入图片描述

6、TCP网络编程

Java语言的基于套接字Socket编程分为客户端和服务端

基于TCP的Socket通信模型

在这里插入图片描述

6.1、基于Socket的TCP编程

1.1客户端Socket的工作过程

  • 创建Socket:根据指定服务端的P地址或端口号构造Sσcket类对象。若服务器端响应,则建立客户端到服务器的通信线路。若连接失败,会出现异常。
  • 打开连接到 Socket的输入出流:使用getInputstream()方法获得输入流,使用getOutputStream()方法获得输出流,进行数据传输
  • 按照一定的协议对Socket进行读/写操作:通过输入流读取服务器放入线路的信息(但不能读取自己放入线路的信息),通过输出流将信息写入线程
  • 关闭 Socket:断开客户端到服务器的连接,释放线路

说明

  • 客户端程序可以使用Socket类创建对象,创建的同时会自动向服务器方发起连接。
  • Socket的构造器是:
    • Socket(String host,int port) throws UnknownHostException,EXCeption:向服务器(域名是host,端口号为port)发起TCP连接,若成功,则创建Socket对象,否则抛出异常。
    • Socket(InetAddress address,int port)throws IOException:根据InetAddress对象所表示的IP地址以及端口号port发起连接
  • 客户端建立 socketAtClient对象的过程就是向服务器发出套接字连接请求

1.2 服务器端Socket的工作过程:

  • 调用ServerSocket(int port):创建一个服务器端套接字,并绑定到指定端口上。用于监听客户端的请求。
  • 调用accept0():监听连接请求,如果客户端请求连接,则接受连接,返回通信套接字对象。
  • 调用该Socket类对象的getOutputStream()和getInputStream():获取输出流和输入流,开始网络数据的发送和接收。
  • 关闭 ServerSocket和Socket对象:客户端访问结束,关闭通信套接字。

说明:

  • ServerSocket对象负责等待客户端请求建立套接字连接,类似邮局某个窗口中的业务员。也就是说,服务器必须事先建立一个等待客户请求建立套接字连接的 Server Socket对象。
  • 所谓“接收”客户的套接字请求,就是 accept()方法会返回一个Socket对象

6.2、实现TCP的网络编程

例子1: 客户端发送信息给服务端,服务端将数据显示在控制台上

 //客户端
    @Test
    public void client(){
        Socket socket = null;
        OutputStream ops = null;
        try {
            InetAddress inetAddress =InetAddress.getByName("127.0.0.1");
            socket = new Socket(inetAddress,123);
            ops = socket.getOutputStream();
            ops.write("你好,我是客户端".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ops!=null){

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

                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //服务端
    @Test
    public void server(){
        Socket accept = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(123);
            accept = ss.accept();
            inputStream = accept.getInputStream();
            baos = new ByteArrayOutputStream();
            byte[] bytes = new byte[5];
            int len;
            while ((len =  inputStream.read(bytes)) != -1){
                 baos.write(bytes,0,len);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null){

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

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

例题2: 客户端发送文件给服务端,服务端将文件保存在本地

 @Test
    public void client(){
        Socket socket = null;
        OutputStream outputStream = null;
        BufferedInputStream bis = null;
        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 20);
            outputStream = socket.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream("1.jpg"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    @Test
    public void server(){
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream inputStream = null;
        BufferedOutputStream bos = null;
        try {
            serverSocket = new ServerSocket(20);
            accept = serverSocket.accept();
            inputStream = accept.getInputStream();
            bos = new BufferedOutputStream(new FileOutputStream("2.jpg"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (accept!=null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

例题3:从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给客户端。

 @Test
    public void client(){
        Socket socket = null;
        OutputStream outputStream = null;
        BufferedInputStream bis = null;
        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 20);
            outputStream = socket.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream("1.jpg"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
            }
            socket.shutdownOutput();
            InputStream inputStream = socket.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] bytes1 = new byte[20];
            int len2;
            while ((len2 = inputStream.read(bytes1)) != -1){
                baos.write(bytes1,0,len2);
            }
            System.out.println(baos.toString());
            baos.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    @Test
    public void server(){
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream inputStream = null;
        BufferedOutputStream bos = null;
        try {
            serverSocket = new ServerSocket(20);
            accept = serverSocket.accept();
            inputStream = accept.getInputStream();
            bos = new BufferedOutputStream(new FileOutputStream("5.jpg"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }
            System.out.println("图片传输完成");
            //服务器端给予客户端反馈
            OutputStream outputStream = accept.getOutputStream();
            outputStream.write("发送成功".getBytes());
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (accept!=null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

7、UDP网络编程(了解)

7.1、简述

  • 类DatagramSocket和DatagramPacket实现了基于UDP协议网络程序。
  • UDP数据报通过数据报套接字DatagramSocket发送和接收,系统不保证UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达。
  • DatagramPacket对象封装了UDP数据报,在数据报中包含了发送端的IP地址和端口号以及接收端的IP地址和端口号
  • UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和接收方的连接。如同发快递包裹一样。

7.2、DatagramSocket类常用方法

在这里插入图片描述

在这里插入图片描述

7.3、DatagramSocket类的使用

  1. DatagramSocket与DatagramPacket
  2. 建立发送端,接收端
  3. 建立数据包
  4. 调用 Socket的发送、接收方法
  5. 关闭 Socket

注意:发送端与接收端是两个独立的运行程序

    //发送端
    @Test
    public void test() throws IOException {
        DatagramSocket ds = new DatagramSocket();
        String str = "我是UDP方式发送的导弹";
        byte[] bytes = str.getBytes();
        InetAddress inetAddress =InetAddress.getLocalHost();
        DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length,inetAddress, 9090);
        ds.send(datagramPacket);
        ds.close();
    }
    //接收端
    @Test
    public void test2() throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(9090);
        byte[] bytes = new byte[100];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);
        datagramSocket.receive(datagramPacket);
        System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
        datagramSocket.close();
    }

8、URL编程

  • URL(Uniform Resource Locator):统一资源定位符,它表示Internet上某一资源的地址。
  • 它是一种具体的URI,即URL可以用来标识一个资源,而且还指明了如何locate这个资源。
  • 通过URL我们可以访问 Internet上的各种网络资源,比如最常见的www,ftp站点。浏览器通过解析给定的URL可以在网络上查找相应的文件或其他资源
  • URL的基本结构由5部分组成: <传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表 例如: http://192.168.1.100:8080/helloworld/indexjsp#a?username=shkstart&password=123 #片段名:即锚点,例如看小说,直接定位到章节 参数列表格式:参数名=参数值&参数名=参数值…

8.1、方法

  • 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 class URLTest {

    public static void main(String[] args) {

        try {

            URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");

//            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();
        }

    }
}

例子:通过URL下载

public class URLTest1 {

    public static void main(String[] args) {

        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL("http://localhost:8080/examples/beauty.jpg");
			//打开连接
            urlConnection = (HttpURLConnection) url.openConnection();
			//连接
            urlConnection.connect();

            is = urlConnection.getInputStream();
            fos = new FileOutputStream("beauty3.jpg");

            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }

            System.out.println("下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(urlConnection != null){
                urlConnection.disconnect();
            }
        }
    }
}

例子: 通过url路径下载音乐

  @Test
    public void test3()  {
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        OutputStream bos = null;
        try {
            URL url = new URL("http://isure.stream.qqmusic.qq.com/C400003Idtm746YJCM.m4a?guid=758114547&vkey=35614D2EF36C66481AA79371B3F8E45194E0A66D4C2B8C8FD7AC964FF9AA725A09C0866205EBE611D75704C6919AE9D1026F895B3A2F61E1&uin=0&fromtag=66");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            inputStream =urlConnection.getInputStream();
            bos = new BufferedOutputStream(new FileOutputStream(new File("D:\\CloudMusic\\4.mp3")));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//            if (urlConnection!=null){
//                urlConnection.disconnect();
//            }
        }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值