Java_ Oriented programming

Tip: after the article is written, the directory can be generated automatically. Please refer to the help document on the right for how to generate it

IP

  • IP address: each computer is assigned an identification number
  • Port: the identity of the application
package Network programming;

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


/*
    InetAddress
        This class represents an Internet Protocol (IP) address
    public static InetAddress getByName(String host): Determine the IP address of the host name. The host name can be either a machine name or an IP address
    public String getHostName(): Gets the host name of this IP address
    public String getHostAddress(): Returns the IP address string in the text display
 */
public class InetAddressDemo {
    public static void main(String[] args) throws UnknownHostException {
        //public static InetAddress getByName(String host): determines the IP address of the host name. The host name can be either a machine name or an IP address
//        InetAddress address = InetAddress.getByName("itheima");
        InetAddress address = InetAddress.getByName("192.168.1.106");

        //public String getHostName(): get the host name of this IP address
        String name = address.getHostName();
        //public String getHostAddress(): returns the IP address string in the text display
        String ip = address.getHostAddress();

        System.out.println("Host name:" + name);
        System.out.println("IP Address:" + ip);
    }
}

UDP

  • UDP protocol is an unreliable network protocol,
  • It establishes a Socket object at both ends of the communication,
  • However, these two sockets are only objects that send and receive data,
  • Therefore, for both sides of communication based on UDP protocol, there is no so-called concept of client and server
  • Java provides DatagramSocket class as a Socket based on UDP protocol

send data

    1:Create sender's Socket object(DatagramSocket)
    2:Create data and package it
    3:call DatagramSocket Object to send data
    4:Close sender
package Network programming.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class SendDemo {
    public static void main(String[] args) throws IOException {
        //Create a Socket object (datagram Socket) at the sending end
        // Datagram socket() constructs a datagram socket and binds it to any available port on the local host
        DatagramSocket ds = new DatagramSocket();

        //Create data and package it
        //DatagramPacket(byte[] buf, int length, InetAddress address, int port)
        //Construct a packet and send the packet with length to the specified port number on the specified host.
        byte[] bys = "send data".getBytes();
//        int length = bys.length;
//        InetAddress address = InetAddress.getByName("192.168.1.106");
//        int port = 10086;
//        DatagramPacket dp = new DatagramPacket(bys,length,address,port);
        DatagramPacket dp = new DatagramPacket(bys,bys.length, InetAddress.getByName("192.168.1.106"),10086);

        //Call the method of DatagramSocket object to send data
        //Void send (datagram packet P) sends datagram packets from this socket
        ds.send(dp);

        //Close sender
        //void close() closes the datagram socket
        ds.close();
    }
}

receive data

    1:Create the of the receiving end Socket object(DatagramSocket)
    2:Create a packet to receive data
    3:call DatagramSocket Object to receive data
    4:Analyze the data package and display the data on the console
    5:Close the receiver
package Network programming.UDP;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        //Create a Socket object (datagram Socket) at the receiving end
        //Datagram socket (int port) constructs a datagram socket and binds it to the specified port on the local host
        DatagramSocket ds = new DatagramSocket(10086);

        //Create a packet to receive data
        //Datagram packet (byte [] buf, int length) constructs a datagram packet for receiving data packets with length
        byte[] bys = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bys,bys.length);

        //Call the method of DatagramSocket object to receive data
        ds.receive(dp);

        //Analyze the data package and display the data on the console
        //byte[] getData() return data buffer
//        byte[] datas = dp.getData();

        //int getLength() returns the length of data to be sent or received
//        int len = dp.getLength();
//        String dataString = new String(datas,0,len);
//        System.out.println("data is:" + dataString);
        System.out.println("The data are:" + new String(dp.getData(),0,dp.getLength()));

        //Close the receiver
        ds.close();
    }
}

TCP

  • TCP communication protocol is a reliable network protocol,
  • He establishes a Socket object at both ends of the communication, so as to establish the network virtual link at both ends of the communication. Once the Le virtual network link is established, the programs at both ends can communicate through the virtual link
  • java provides a good package for the network based on TCP protocol. Socket objects are used to represent the communication ports at both ends,
  • And generate IO flow through Socket for network communication
  • Java provides a Socket class for the client and a ServerSocket class for the server

send data

TCP To send data
    1:Create client Socket object(Socket)
    2:Get output stream and write data
    3:Release resources
package Network programming.TCP;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class ClientDemo {
    public static void main(String[] args) throws IOException {
        //Create the client's Socket object (Socket)
        //Socket (InetAddress, int port) creates a stream socket and connects it to the specified port number of the specified IP address
//        Socket s = new Socket(InetAddress.getByName("192.168.1.106"),10000);
        //Socket(String host, int port) creates a stream socket and connects it to the specified port number on the specified host
        Socket s = new Socket("192.168.1.106",10000);

        //Get output stream and write data
        //OutputStream getOutputStream() returns the output stream of this socket
        OutputStream os = s.getOutputStream();
        os.write("send data".getBytes());

        //Release resources
        s.close();
    }
}

receive data

TCP Steps to receive data
    1:Create server-side Socket object(ServerSocket)
    2:Get the input stream, read the data, and display the data on the console
    3:Release resources
package Network programming.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
    public static void main(String[] args) throws IOException {
        //Create a server-side Socket object (ServerSocket)
        //ServerSocket(int port) creates a server socket bound to a specified port
        ServerSocket ss = new ServerSocket(10000);

        //Socket accept() listens for the socket to be connected to and accepts it
        Socket s = ss.accept();

        //Get the input stream, read the data, and display the data on the console
        InputStream is = s.getInputStream();

        byte[] bys = new byte[1024];
        int len = is.read(bys);
        String data = new String(bys,0,len);
        System.out.println("The data are:" + data);

        //Release resources
        s.close();
        ss.close();
    }
}

Small case

Case requirements

  • Client: the data comes from the keyboard input until the input data is 88 and the sending of data ends
  • Server: the received data is output on the console

case analysis

  • The client creates an object, uses the keyboard to enter, circularly accepts data, accepts one line and sends one line until the keyboard enters 88
  • The server creates an object and uses the input stream to receive data circularly by line until null is accepted

client

package Network programming.TCP.test2;

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

/*
    Client: the data comes from the keyboard input until the input data is 886, and the sending of data ends
 */
public class ClientDemo {
    public static void main(String[] args) throws IOException {
        //Create a client Socket object
        Socket s = new Socket("192.168.1.106",10000);

        //The data comes from the keyboard input until the input data is 88 and the sending of data ends
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        //Encapsulate output stream objects
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        String line;
        while ((line=br.readLine())!=null) {
            if("886".equals(line)) {
                break;
            }

            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        //Release resources
        s.close();
    }
}

The server

package Network programming.TCP.test2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/*
    Server: the received data is output on the console
 */
public class ServerDemo {
    public static void main(String[] args) throws IOException {
        //Create server Socket object
        ServerSocket ss = new ServerSocket(10000);

        //Listen to the connection of the client and return a corresponding Socket object
        Socket s = ss.accept();

        //Get input stream
//        InputStream is = s.getInputStream();
//        InputStreamReader isr = new InputStreamReader(is);
//        BufferedReader br = new BufferedReader(isr);
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        //Release resources
        ss.close();
    }
}

Tags: Java network udp

Posted by ocpaul20 on Sat, 21 May 2022 23:45:58 +0300