编程知识 cdmana.com

Baozi series -- Java basics Chapter 14_ Network programming

Chapter 14 Network programming

image-20201111202804994.png

InetAddress class

Two problems need to be solved to realize network communication

  1. How to accurately locate one or more hosts on the network ; Locate specific applications on the host
  2. How to transfer data reliably and efficiently after finding the host

Two elements of network communication

  1. Corresponding to question 1 :IP And port number
  2. Corresponding to question 2 : Provide network communication protocol :TCP/IP Reference model ( application layer 、 Transport layer 、 The network layer 、 Physics + Data link layer )

Communication element 1 :IP And port number

IP The understanding of the

  1. IP: The only sign Internet Computers on ( Communication entities )
  2. stay Java Use in InetAddress Class representative IP
  3. IP classification :IPv4 and IPv6 ; web and LAN
  4. domain name : www.baidu.com www.mi.com www.sina.com www.jd.com
  5. Local loop address :127.0.0.1 Corresponding :localhost

Domain name resolution : Domain names are easy to remember , When connecting to the network, enter the domain name of a host , Domain name server (DNS) Responsible for translating domain names into IP Address , In this way, we can establish a connection with the host . ------- Domain name resolution

Port number and IP The combination of addresses leads to a network socket :Socket.

InetAddress class : An object of this class represents a specific IP Address

Internet There are two ways for a host on to represent an address :

  • domain name (hostName):www.atguigu.com
  • IP Address (hostAddress):202.108.35.210

InetAddress Class mainly represents IP Address , Two subclasses :Inet4Address、Inet6Address.

InetAddress class Yes like contain Yes One individual Internet Lord machine The earth site Of Domain name and IP The earth site : www.atguigu.com and 202.108.35.210.

Instantiation

netAddress Class does not provide a public constructor , Instead, it provides the following static methods to get InetAddress example

getByName(String host) 、 getLocalHost()

public static InetAddress getLocalHost()

public static InetAddress getByName(String host)

Common methods

getHostName() / getHostAddress()

public String getHostAddress(): return  IP  Address string ( In the form of text ).

public String getHostName(): Access to this  IP  The host name of the address 

Example

image-20201111193816114.png

Port number

A process that is running on a computer

  • requirement : Different processes have different port numbers
  • Range : To be defined as a 16 An integer 0~65535.
  • Port number and IP The combination of addresses leads to a network socket :Socket

Communication element 2 : Network communication protocol

Classification model

image-20201111193924155.png

TCP and UDP The difference between

image-20201111193935618.png

TCP Three handshakes and four waves

image-20201111194012602.png

image-20201111194102042.png

Socket classification

  • Stream Socket (stream socket): Use TCP Provide reliable byte stream Services
  • Socket datagram (datagram socket): Use UDP Provide “ Do my best ” Datagram service for

TCP Network programming

be based on Socket Of TCP Programming

image-20201111194439483.png

client Socket There are four basic steps in the process :

  • establish Socket: According to the specified server IP Address or port number construction Socket Class object . If the server side Respond to , Then establish the communication line from the client to the server . If the connection fails , There will be anomalies .
  • Open the connection to Socket The input of / Outflow : Use getInputStream() Method to get the input stream , Use getOutputStream() Method to get the output stream , Data transfer
  • According to a certain agreement Socket Read / Write operations : Read the information that the server put into the line through the input stream ( But I can't read the information I put in the line ), Write information to the thread through the output stream .
  • close Socket: Disconnect the client from the server , Release the line

The working process of the server program includes the following four basic steps

  • call ServerSocket(int port) : Create a server socket , And bind to the specified port On . Used to listen for requests from clients
  • call accept(): Listen for connection requests , If the client requests a connection , Then accept the connection , Back to communication Socket object
  • call The Socket Class object getOutputStream() and getInputStream (): Get output Streams and input streams , Start sending and receiving network data .
  • close ServerSocket and Socket object : End of client access , Close communication socket .

Code example 1 Send a message

The client sends information to the server , The server displays the data on the console

// client 
@Test
public void client()  {
    Socket socket = null;
    OutputStream os = null;
    try {
        //1. establish Socket object , Indicates the server side of ip And port number 
        InetAddress inet = InetAddress.getByName("192.168.14.100");
        socket = new Socket(inet,8899);
        //2. Get an output stream , Used to output data 
        os = socket.getOutputStream();
        //3. The operation of writing data 
        os.write(" Hello , I'm the client mm".getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4. Closure of resources 
        if(os != null){
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

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

        }
    }
}
// Server side 
@Test
public void server()  {

    ServerSocket ss = null;
    Socket socket = null;
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    try {
        //1. Create server side ServerSocket, Indicate your own port number 
        ss = new ServerSocket(8899);
        //2. call accept() Represents the reception of socket
        socket = ss.accept();
        //3. Get input stream 
        is = socket.getInputStream();

        // It's not recommended to write , It could be messy 
        //        byte[] buffer = new byte[1024];
        //        int len;
        //        while((len = is.read(buffer)) != -1){
        //            String str = new String(buffer,0,len);
        //            System.out.print(str);
        //        }
        //4. Read data from the input stream 
        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(" Received from :" + socket.getInetAddress().getHostAddress() + " The data of ");

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(baos != null){
            //5. close resource 
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(is != null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(socket != null){
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(ss != null){
            try {
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

Code example 2 Upload files

The client sends the file to the server , The server saves the file locally

@Test
public void client() throws IOException {
    //1.
    Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
    //2.
    OutputStream os = socket.getOutputStream();
    //3.
    FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
    //4.
    byte[] buffer = new byte[1024];
    int len;
    while((len = fis.read(buffer)) != -1){
        os.write(buffer,0,len);
    }
    //5.
    fis.close();
    os.close();
    socket.close();
}
@Test
public void server() throws IOException {
    //1.
    ServerSocket ss = new ServerSocket(9090);
    //2.
    Socket socket = ss.accept();
    //3.
    InputStream is = socket.getInputStream();
    //4.
    FileOutputStream fos = new FileOutputStream(new File("beauty1.jpg"));
    //5.
    byte[] buffer = new byte[1024];
    int len;
    while((len = is.read(buffer)) != -1){
        fos.write(buffer,0,len);
    }
    //6.
    fos.close();
    is.close();
    socket.close();
    ss.close();

}

Code example 3 Return the document , Return information

@Test
public void client() throws IOException {
    //1.
    Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
    //2.
    OutputStream os = socket.getOutputStream();
    //3.
    FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
    //4.
    byte[] buffer = new byte[1024];
    int len;
    while((len = fis.read(buffer)) != -1){
        os.write(buffer,0,len);
    }
    // Turn off the output of data 
    socket.shutdownOutput();

    //5. Receiving data from the server , And display it on the console 
    InputStream is = socket.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] bufferr = new byte[20];
    int len1;
    while((len1 = is.read(buffer)) != -1){
        baos.write(buffer,0,len1);
    }

    System.out.println(baos.toString());

    //6.
    fis.close();
    os.close();
    socket.close();
    baos.close();
}
@Test
public void server() throws IOException {
    //1.
    ServerSocket ss = new ServerSocket(9090);
    //2.
    Socket socket = ss.accept();
    //3.
    InputStream is = socket.getInputStream();
    //4.
    FileOutputStream fos = new FileOutputStream(new File("beauty2.jpg"));
    //5.
    byte[] buffer = new byte[1024];
    int len;
    while((len = is.read(buffer)) != -1){
        fos.write(buffer,0,len);
    }

    System.out.println(" Picture transfer complete ");

    //6. The server gives the client feedback 
    OutputStream os = socket.getOutputStream();
    os.write(" Hello , beauty , I have received the picture , Very beautiful !".getBytes());

    //7.
    fos.close();
    is.close();
    socket.close();
    ss.close();
    os.close();

}

Summary

Left server 、 Right client

image-20201111195701881.png

client

  • Customize
  • browser

Server side

  • Customize
  • Tomcat The server

UDP Network programming

class DatagramSocket and DatagramPacket Based on UDP Protocol network program .

UDP Datagram through datagram socket DatagramSocket Send and receive , The system does not guarantee UDP Datagrams must be delivered safely to their destinations , I'm not sure when I'll arrive

DatagramPacket Object encapsulates UDP The datagram , The datagram contains the sender's IP Address and port number as well as the receiver's IP Address and port number

UDP Each datagram in the protocol gives the complete address information , Therefore, there is no need to establish a connection between the sender and the receiver . It's like sending an express package .

technological process

  1. DatagramSocket And DatagramPacket
  2. Set up the sender , The receiver
  3. Building packets
  4. call Socket Sending of 、 Receiving method
  5. close Socket

The sender and receiver are two independent running programs

Example 1

The sender

DatagramSocket ds = null;
try {
    ds = new DatagramSocket();
    byte[] by = "hello,atguigu.com".getBytes();
    DatagramPacket dp = new DatagramPacket(by, 0, by.length, InetAddress.getByName("127.0.0.1"), 10000);
    ds.send(dp);
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (ds != null)
        ds.close();
}

The receiver

DatagramSocket ds = null;
try {
    ds = new DatagramSocket(10000);
    byte[] by = new byte[1024];
    DatagramPacket dp = new DatagramPacket(by, by.length);
    ds.receive(dp);
    String str = new String(dp.getData(), 0, dp.getLength());
    System.out.println(str + "--" + dp.getAddress());
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (ds != null)
    ds.close();
}

Code example

// The sender 
@Test
public void sender() throws IOException {

    DatagramSocket socket = new DatagramSocket();

    String str = " I am a UDP Missiles sent by ";
    byte[] data = str.getBytes();
    InetAddress inet = InetAddress.getLocalHost();
    DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);

    socket.send(packet);

    socket.close();

}
// The receiver 
@Test
public void receiver() throws IOException {

    DatagramSocket socket = new DatagramSocket(9090);

    byte[] buffer = new byte[100];
    DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);

    socket.receive(packet);

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

    socket.close();
}

URL Programming

URL(Uniform Resource Locator): Uniform resource locator , It said Internet On a certain The address of the resource .

URL Of 5 The basic structure

http://localhost:8080/examples/beauty.jpg?username=Tom

agreement Host name Port number Resources to address parameter list

How to instantiate

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

Common methods

One URL After the object is generated , Its properties cannot be changed , But it can be given by Method to get these properties :

public String getProtocol( )  Get the URL The agreement name of 
public String getHost( )  Get the URL The host name 
public String getPort( )  Get the URL Port number 
public String getPath( )  Get the URL File path 
public String getFile( )  Get the URL The name of the file 
public String getQuery( )  Get the URL The query name of 
URL url = new URL("http://localhost:8080/examples/myTest.txt");
System.out.println("getProtocol() :"+url.getProtocol());
System.out.println("getHost() :"+url.getHost());
System.out.println("getPort() :"+url.getPort());
System.out.println("getPath() :"+url.getPath());
System.out.println("getFile() :"+url.getFile());
System.out.println("getQuery() :"+url.getQuery());

//=============================
getProtocol() :http
getHost() :localhost
getPort() :8080
getPath() :/examples/myTest.txt
getFile() :/examples/myTest.txt
getQuery() :null

Can read 、 Download the corresponding url resources

URLConnection: To URL Connection of the referenced remote object . When with a URL When establishing a connection , First of all, in a URL By means of objects openConnection() Generate corresponding URLConnection object . If the connection process fails , Will produce IOException.

adopt URLConnection Object to get the input stream and output stream , That is, it can be compared with the existing CGI Programs interact .

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("day10\\beauty3.jpg");

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

        System.out.println(" Download complete ");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // close resource 
        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();
        }
    }
}

URI、URL and URN The difference between

URI, yes uniform resource identifier, Uniform resource identifiers , Used to uniquely identify a resources . and URL yes uniform resource locator, Uniform resource locator , It's a kind of concrete Of URI, namely URL Can be used to identify a resource , It also shows how to locate This resource .

and URN,uniform resource name, Unified resource naming , Resources are identified by their names , such as mailto:java-net@java.sun.com.

in other words ,URI In an abstract way , high-level The sub concept defines the uniform resource identifier , and URL and URN It's a specific way to identify resources .URL and URN Is a kind of URI.

版权声明
本文为[Want to exchange steamed stuffed bun for thesis]所创,转载请带上原文链接,感谢

Scroll to Top