java foundation---network programming

java basics - network programming

1. Network Reference Mode

  • OIS (Open System Interconnection Open System Interconnection) reference model.

    • packet transmission process
  • TCP/IP reference model (TCP/IP model is a simplified model of OIS)

  • Seven layers description:

    1. Physical layer: It mainly defines the standards of physical equipment, such as the interface type of network cable, the interface type of optical fiber, and the transmission rate of various transmission media. Its main function is to transmit the bit stream (that is, it is converted from 1, 0 to current strength for transmission, and then converted to 1, 0 after reaching the destination, which is what we often call digital-to-analog conversion and analog-to-digital conversion). This layer of data is called bits.

    2. Data link layer: It mainly encapsulates and decapsulates the MAC address (address of the network card) of the data received from the physical layer. This layer of data is often referred to as a frame. The device working at this layer is the switch, and data is transmitted through the switch.

    3. Network layer: It mainly encapsulates and decapsulates the IP address (for example, 192.168.0.1) of the data received by the lower layer. The device working at this layer is a router, and the data at this layer is often called a data packet.

    4. Transport layer: defines some protocols and port numbers for data transmission (WWW port number 80, etc.), such as: TCP (Transmission Control Protocol, low transmission efficiency, strong reliability, used for transmitting data with high reliability requirements and a large amount of data) ), UDP (User Datagram Protocol, which is the exact opposite of TCP characteristics, is used to transmit data with low reliability requirements and a small amount of data, such as QQ chat data is transmitted in this way). It is mainly to segment and transmit the data received from the lower layer, and then reassemble after reaching the destination address. This layer is often called a segment.

    5. Session layer: establishes a data transmission path through the transport layer (port number: transmit port and receive port). Mainly initiate sessions or receive session requests between your systems (devices need to know each other by IP or MAC or hostname).

    6. Presentation layer: It mainly interprets the received data, encrypts and decrypts, compresses and decompresses, etc.

    7. Application layer: mainly some terminal applications, such as FTP (various file download), WEB (IE browsing), QQ and the like (it can be understood as what we can see on the computer screen, which is the terminal application ).

The elements of network communication

  1. IP address: InetAddress

    • Identification of devices in the network

    • Not easy to remember, you can use the host name.

InetAddress ip = InetAddress.getLocalHost(); //获取本地主机IP地址对象
String adress=ip.getHostAddress();//返回 IP 地址字符串
String name=ip.getHostName();//获取此 IP 地址的主机名。
  1. The port number

    • The logical address used to identify the process (application), the identification of different processes.

    • Valid ports: 0~65535, of which 0~1024 are used or reserved ports by the system.

  2. Transmission protocol (rules of communication)

    • **Common protocols:**UDP, TCP.

    • Features of UDP:

      • Encapsulates data and source and destination into packets without establishing a connection.

      • The size of each datagram is limited to 64k.

      • Because there is no connection, it is an unreliable protocol.

      • There is no need to establish a connection and the speed is fast.

    • Features of TCP:

      • A connection is established to form a channel for transmitting data.

      • Transfer large amounts of data within a connection.

      • The connection is completed through a three-way handshake and is a reliable protocol.

      • A connection must be established, which will be slightly less efficient.

3. Domain name resolution

  • For domain name resolution, the first step is the local hosts (C:\WINDOWS\system32\drivers\etc\hosts) file. If the resolution fails, the DNS server is accessed to resolve and obtain the IP address.

Fourth, UDP protocol - sender & receiver

  • Socket

    • Socket is a mechanism provided for network services.

    • There are sockets at both ends of the communication.

    • Network communication is actually communication between sockets.

    • Data is transferred between two Sockets through IO.

  • UDP transport

    • DatagramSocket (socket used to send and receive datagram packets) and DatagramPacket (datagram packets).

    • Create sender and receiver.

    • Build packets.

    • Call the send and receive methods of the Socket.

    • Close the socket.

    • The sender and receiver are two independent running programs.

  • Example:

    • UDP sender:
import java.net.*;
class UDPSendDemo 
{
    public static void main(String[] args) throws Exception
    {
        System.out.println("…………发送端启动");

        //如果发送端端口未指定,就会随机分配未被使用的端口。
        DatagramSocket ds=new DatagramSocket(8888);
        String str="UDP来了,请查收!";
        byte[] buf=str.getBytes();

        //使用DatagramPacket将数据封装到该对象包中。
        DatagramPacket dp=
            new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.103"),10000);
        // 通过udp的socket服务将数据包发送出去,使用send方法。
        ds.send(dp);
        ds.close();
    }
}
  • UDP receiver
import java.net.*;
class  UDPReceDemo
{
    public static void main(String[] args) throws Exception
    {
        System.out.println("…………接收端启动");

        //建立UPDsocket服务。
        DatagramSocket ds=new DatagramSocket(10000);

        //创建数据包。
        byte[] buf =new byte[1024];
        DatagramPacket dp=new DatagramPacket(buf,buf.length);

        // 使用接收方法将数据存储到数据包中。
        ds.receive(dp);

        // 通过数据包对象的方法,解析其中的数据,比如:地址,端口,数据内容
        String ip=dp.getAddress().getHostAddress();
        int port=dp.getPort();
        String text=new String (dp.getData(),0,dp.getLength());
        System.out.println(ip+"--"+port+"--"+text);
        //关闭资源
        ds.close();
    }
}
  • Output result:
    write picture description here

Five, TCP protocol (client & server)

  • TCP protocol: The client (Client) first establishes a connection with the server (Server) to form a channel (in fact, an IO stream), and then data can be transmitted between channels, and a single server can communicate with multiple clients at the same time. establish connection.

  • TCP client:

    • The client needs to specify the ip address and port of the server so that it can try to establish a connection. If the connection fails, an exception will occur. The connection is successful, indicating that the client and the server have established a channel, then data transmission can be performed through the IO stream, and the Socket object has provided input stream and output stream objects, which can be
      getInputStream(),getOutputStream()obtained by . After the communication with the server ends, close the Socket.
  • TCP server:

    • The server needs to know which port the data it wants to process is coming in from. When a client accesses, to determine which client it is, you can obtain the connected client object through accept(), and use this object to transfer data with the client through IO streams. When the client access ends, close the client.
  • Example (text conversion):

    • Client:
import java.io.*;
import java.net.*;
class  TransClient
{
    public static void main(String[] args) throws Exception
    {
        //建立Socket客户端
        Socket s=new Socket("192.168.0.103",10000);
        //获取键盘录入
        BufferedReader br=
            new BufferedReader(new InputStreamReader(System.in));
        //socket输入流,获取服务端返回的大写数据
        BufferedReader br1=
            new BufferedReader(new InputStreamReader(s.getInputStream()));
        //socket输出流
        PrintWriter pw=
            new PrintWriter(s.getOutputStream(),true);
        String line=null;
        while ((line=br.readLine())!=null)
        {
            if ("over".equals(line))
            {
                break;
            }
            pw.println(line);
            //读取服务端发回来的数据
            String str=br1.readLine();
            System.out.println(str);
        }   
        s.close();
    }
}
  • Server
import java.io.*;
import java.net.*;
class  TransServer
{
    public static void main(String[] args) throws Exception

        //创建服务端ServerSocket
        ServerSocket ss=new ServerSocket(10001);
        //获取Socket对象
        Socket s=ss.accept();
        //获取ip
        String ip=s.getInetAddress().getHostAddress();
        System.out.println(ip+"……………connect");
        //获取Socket输出流并装饰
        PrintWriter pw=
            new PrintWriter(s.getOutputStream(),true);
        //获取Socket读取流并装饰
        BufferedReader br=
            new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line=null;
        while ((line=br.readLine())!=null)
        {
            System.out.println(line);
            //将客户端发过来的信息转为大写后发送给客户端
            pw.println(line.toUpperCase());
        }
        s.close();
        ss.close();
    }
}
  • Output result:
    write picture description here
    write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325544458&siteId=291194637