day16+17+18+19网络编程

文章目录

  • 网络编程
    • 1.概述
    • 2.网络通信的两个要素
    • 小结
    • 2.1 IP地址
    • 2.2 端口Port
    • 2.3 通信协议
    • 3.TCP
      • 客户端
      • 服务器端
      • TCP实现文件上传
    • 4. UDP
      • UDP实现发送消息
    • 5. Tomcat
    • 6. URL
      • 下载资源
      • 下载网络资源

网络编程

1.概述


所谓的计算机网络是指通过某种方式将多台计算机进行连接,它实现了多台计算机彼此之间的互联以及数据交换。位于同一个网络中的计算机若想实现彼此间的通信,必须通过编写网络程序来实现,即在不同的计算机上编写一些实现了网络连接的程序,这些程序可以实现数据的交换。

javaweb:网页编程——B/S 浏览器/服务器架构

网络编程——TCP/IP——C/S 客户端/服务器架构

2.网络通信的两个要素


IP地址和端口号网络通信协议

IP地址:要想使网络中的计算机能够进行通信,必须为每台计算机指定一个标识号,通过这个标识号来指定接收数据的计算机或者发送数据的计算机。在TCP/IP协议中,这个标识号就是IP地址,它可以唯一标识一台计算机。

端口号:通过IP地址可以连接到指定计算机,但如果想访问目标计算机中的某个应用程序,还需要指定端口号。在计算机中,不同的应用程序是通过端口号区分的。端口号是用两个字节(16位的二进制数)表示的,它的取值范围是065535,其中01023之间的端口号用于一些知名的网络服务和应用,用户的普通应用程序需要使用1024以上的端口号,从而避免端口号被另一个应用或服务所占用。

(位于网络中的一台计算机可以通过IP地址去访问另一台计算机,并通过端口号访问目标计算机中的某个应用程序)

网络通信协议:通过计算机网络可以使多台计算机实现连接,位于同一个网络中的计算机在进行连接和通信时需要遵守一定的规则,这就好比在道路中行驶的汽车一定要遵守交通规则一样。在计算机网络中,这些连接和通信的规则被称为网络通信协议,它对数据的传输格式、传输速率、传输步骤等做了统一规范,通信双方必须同时遵守才能完成数据交换。

TCP/IP参考模型

OSI七层网络模型 TCP/IP四层概念模型 对应网络协议
应用层(Application) 应用层 HTTP、TFTP、FTP、NFS、WAIS、SMTP
表示层(Presentation) 同上~ Telnet、Plogin、SNMP、Gopher
会话层(Session) 同上~ SMTP、DNS
传输层(Transport) 传输层 TCP、UDP
网络层(NetWork) 网络层 IP、ICMP、ARP、RARP、AKP、UUCP
数据链路层(Data Link) 链路层 FDDI、Ethernet、Arpanet、PDN、SLIP、PPP
物理层(Physical) 同上~ IEEE 802.1A、IEEE 802.2到IEEE 802.11

TCP/IP协议中的四层分别是应用层、传输层、网络层和链路层

应用层:主要负责应用程序的协议,如HTTP协议、FTP协议等。

传输层:主要是网络程序进行通信,在进行网络通信时,可以采用TCP协议也可以采用UDP协议。

网络层:网络层是整个TCP/IP协议的核心,它主要用于将传输的数据进行分组,将分组数据传送发送到目标计算机或者网络。

链路层:链路层用于定义物理传输通道,通常是对某些网络连接设备的驱动协议,例如针对光纤、双绞线提供的驱动。

小结


1、网络编程中有两个主要的问题

  • 如何准确的定位到网络上的一台或者多台主机
  • 找到主机之后如何进行通信

2、网络编程中的要素

  • IP地址和端口号 — IP
  • 网络通信协议 — UDP,TCP

2.1 IP地址


ip地址:InetAddress

IP地址:要想使网络中的计算机能够进行通信,必须为每台计算机指定一个标识号,通过这个标识号来指定接收数据的计算机或者发送数据的计算机。在TCP/IP协议中,这个标识号就是IP地址,它可以唯一标识一台计算机。

IP可以用来唯一定位一台网络上的计算机

  • 127.0.0.1 本机 localhost

ip地址分类:

  1. ip地址分类:

    ipv4:127.0.0.1 四个字节组成(0~255)

    ipv6:128位,8个无符号整数

  2. 公网(互联网)–私网(局域网)分类:

  • ABCD类地址
  • 192.168.xx.xx,专门给组织内部使用的

域名:记忆IP问题

package com.mollzz.ip;

import java.net.InetAddress;
import java.net.UnknownHostException;

//测试IP
public class TestInetAddress {
    public static void main(String[] args) {
        try {
            //查询本机地址:3种方法
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress1);

            InetAddress inetAddress3 = InetAddress.getByName("localhost");
            System.out.println(inetAddress3);

            InetAddress inetAddress4 = InetAddress.getLocalHost();
            System.out.println(inetAddress4);

            //查询网站ip地址
            InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress2);


        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }
}

2.2 端口Port


(Ctrl+Shift+Esc 打开任务管理器可查看进程)

端口号:通过IP地址可以连接到指定计算机,但如果想访问目标计算机中的某个应用程序,还需要指定端口号。在计算机中,不同的应用程序是通过端口号区分的。端口号是用两个字节(16位的二进制数)表示的,它的取值范围是065535,其中01023之间的端口号用于一些知名的网络服务和应用,用户的普通应用程序需要使用1024以上的端口号,从而避免端口号被另一个应用或服务所占用。

端口表示计算机上的一个程序的进程

  • 不同的进程有不同的端口号!用来区分软件。端口号不可冲突
  • 被规定0~65535
  • TCP,UDP 共有 :65535 * 2,单个协议下,端口号不能冲突

端口分类

  • 公有端口(0~1023)

    HTTP:80

    HTTPS:443

    FTP:21

    Telent:23

  • 程序注册端口(1024~49151),分配给用户或程序

    Tomcat:8080

    MySQL:3306

    Oracle:1521

  • 动态、私有端口(49152~65535)

    查看所有端口:

    netstat -ano
    

    查看指定端口:

    netstat -ano|findstr "5900"
    

    查看指定端口的进程:

    tasklist|findstr "8696"
    
package com.mollzz.internet;

import java.net.InetSocketAddress;

public class TestInetSocketAddress {
    public static void main(String[] args) {

        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
        InetSocketAddress socketAddress2 = new InetSocketAddress("localhost", 8080);
        System.out.println(socketAddress);
        System.out.println(socketAddress2);

        System.out.println(socketAddress.getAddress());
        System.out.println(socketAddress.getHostName());
        System.out.println(socketAddress.getPort());
    }
}

2.3 通信协议


网络通信协议:通过计算机网络可以使多台计算机实现连接,位于同一个网络中的计算机在进行连接和通信时需要遵守一定的规则,这就好比在道路中行驶的汽车一定要遵守交通规则一样。在计算机网络中,这些连接和通信的规则被称为网络通信协议,它对数据的传输格式、传输速率、传输步骤等做了统一规范,通信双方必须同时遵守才能完成数据交换。

TCP/IP协议簇,实际上是一组协议。

传输层两个重要的高级协议:

  • TCP:用户传输协议
  • UDP:用户数据报协议

TCP与UDP对比

TCP:

  • 面向连接,稳定
  • 客户端、服务器端
  • 三次握手,四次挥手
  • 传输完成,释放连接,效率低

UDP:

  • 无连接,不稳定
  • 客户端、服务端没有明确界限
  • 不管有没有准备好,都可以发送

3.TCP


客户端

  1. 连接服务器 Socket
  2. 发送消息
package com.mollzz.tcp;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

//客户端
public class TcpClientDemo01 {
    public static void main(String[] args) {

        Socket socket=null;
        OutputStream os=null;

        try {
            //1.要知道服务器地址
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            //  端口号
            int port=9999;
            //2.创建一个socket连接
            socket=new Socket(serverIP,port);
            //3.发送消息IO流
            os=socket.getOutputStream();
            os.write("你好-------------".getBytes());

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
}

服务器端

  1. 建立服务的端口 ServerSocket
  2. 等待用户的链接 accept
  3. 接收用户的消息
package com.mollzz.tcp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class TcpServerDemo01 {
    public static void main(String[] args) {

        ServerSocket serverSocket=null;
        Socket socket =null;
        InputStream is =null;
        ByteArrayOutputStream baos=null;
        try {
            //1.得有一个地址
            serverSocket=new ServerSocket(9999);
            //2.等待客户端连接
            socket = serverSocket.accept();
            //3.读取客户端消息
            is = socket.getInputStream();

            //管道流
            baos=new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len=is.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭资源
            //先开后关
            if (baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

TCP实现文件上传


客户端

package com.mollzz.tcp;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;


public class TcpClientDemo02 {
    public static void main(String[] args) throws Exception {
        //1.创建一个Socket连接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
        //2.创建一个输出流
        OutputStream os = socket.getOutputStream();

        //3.读取文件
        FileInputStream fis = new FileInputStream(new File("bengtie.png"));
        //4.写出文件
        byte[] buffer = new byte[1024];
        int len;
        while((len=fis.read(buffer))!=-1){
            os.write(buffer,0,len);
        }

        //通知服务器,我已经结束了
        socket.shutdownOutput();//我已经传输完毕

        //确定服务器接收完毕,才能够断开连接
        InputStream inputStream=socket.getInputStream();
        ByteArrayOutputStream baos=new ByteArrayOutputStream();

        byte[] buffer2=new byte[1024];
        int len2;
        while((len2=inputStream.read(buffer2))!=-1){
            baos.write(buffer2,0,len2);
        }

        //5.关闭资源
        baos.close();
        inputStream.close();
        fis.close();
        os.close();
        socket.close();

    }
}

服务器端

package com.mollzz.tcp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpServerDemo02 {
    public static void main(String[] args) throws Exception {
        //1.创建服务
        ServerSocket serverSocket = new ServerSocket(9000);
        //2.监听客户端的连接
        Socket socket = serverSocket.accept();//阻塞式监听,会一直等待客户端连接
//        Scanner scanner = new Scanner(System.in);
//        scanner.next();
        //3.获取输入流
        InputStream is = socket.getInputStream();
        //4.文件输出
        FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }

        //通知客户端我接收完毕了
        OutputStream os=socket.getOutputStream();
        os.write("我接收完毕了,你可以断开了!".getBytes());

        //关闭资源
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

4. UDP


UDP实现发送消息

发送端:send

package com.mollzz.udp;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

//不需要连接服务器
public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        //1.建立一个Socket
        DatagramSocket socket=new DatagramSocket(8080);

        //2.建个包
        String msg="你好,服务器";
        //发送给谁
        InetAddress localhost=InetAddress.getByName("localhost");
        int port=9090;
        //数据,数据长度起始,发送给谁
        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);

        //3.发送包
        socket.send(packet);

        //4.关闭流
        socket.close();

    }

}

接收端:receive

package com.mollzz.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
        //开放端口
        DatagramSocket socket=new DatagramSocket(9090);
        //接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);//接收

        socket.receive(packet);//阻塞接收

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

        //关闭连接
        socket.close();
    }
}

5. Tomcat

服务端

  • 自定义 S
  • Tomcat服务器 S:Java后台开发!

客户端

  • 自定义 C
  • 浏览器 B

启动tomcat服务:apache-tomcat安装路径下——>bin 目录——> 找到 startup.bat文件,双击启动

6. URL

URL,统一资源定位符,是对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示,是互联网上标准资源的地址。

DNS域名解析,通过DNS解析将域名转化为IP地址。

协议://ip地址:端口号/项目名/资源

package com.mollzz.url;

import java.net.MalformedURLException;
import java.net.URL;

public class URLDemo01 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=mollzz&password=123");
        System.out.println(url.getProtocol());//协议名
        System.out.println(url.getHost());//主机
        System.out.println(url.getPort());//端口
        System.out.println(url.getPath());//文件地址
        System.out.println(url.getFile());//全路径
        System.out.println(url.getQuery());//参数
    }
}

下载资源

package com.mollzz.url;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class URLDown {
    public static void main(String[] args) throws Exception {
        //1.下载地址
        URL url = new URL("http://localhost:8080/mollzz/secretFile.txt");

        //2.连接到这个资源 HTTP、
        HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("secretFile.txt");

        byte[] buffer = new byte[1024];
        int len;
        while((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0, len);//写出这个数据
        }

        //关闭
        fos.close();
        inputStream.close();
        urlConnection.disconnect();//断开连接
    }
}

下载网络资源

package com.mollzz.url;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class URLDown {
    public static void main(String[] args) throws Exception {
        //1.下载地址
//        URL url = new URL("https://m801.music.126.net/20240203192929/ecee31ace133c2b92b95826786f11cb2/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/33247829320/e6ec/2c36/400c/26669355bee79b5f6a90c2e160b097e0.m4a");
        URL url = new URL("https://p1.music.126.net/0CK7y3YKcvzoy4QqW1BMnw==/109951169300789480.jpg?param=200y200");

        //2.连接到这个资源 HTTP、
        HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

//        FileOutputStream fos = new FileOutputStream("Imfine.mp4");
        FileOutputStream fos = new FileOutputStream("109951169300789480.jpg");

        byte[] buffer = new byte[1024];
        int len;
        while((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0, len);//写出这个数据
        }

        //关闭
        fos.close();
        inputStream.close();
        urlConnection.disconnect();//断开连接
    }
}

你可能感兴趣的:(学习,网络,java)