Java network programming summary

Java network programming summary

1.1 general

Letter:

Computer network:
Computer network refers to a computer system that connects multiple computers and their external devices with independent functions in different geographical locations through communication lines and realizes resource sharing and information transmission under the management and coordination of network operating system, network management software and network communication protocol.
Purpose of network programming:
Radio stations... Transmit and exchange information, data exchange, communication
What is needed to achieve this effect:
1. How to accurately locate a host 192.168.16.24: port on the network and locate a resource on the computer
2. After finding the host, how to transmit data?
javaweb: Web programming B/S browser / server
Network programming: TCP/IP C/S client / server

1.2 elements of network communication

How to realize network communication?
Address of both parties:

  • ip
  • Port number
  • 192.168.16.124: 5900
    Rules: network communication protocol
    TCP/IP reference
  • Summary:
    1. There are two main problems in network programming
    • How to accurately locate one or more hosts on the network
    • How to communicate after finding the host
      2. Elements in network programming
    • IP and port number
    • Network communication protocol
      3. All things are objects

1.3 IP

Address: inetap

  • Uniquely locate a computer on the network
  • 127.0.0.1: local localhost
  • Classification of ip addresses
    • ipv4/ipv6
      • IPv4 127.0.0.1 consists of four bytes. 0-255.42 billion ~;
      • ipv6: 128 bit. 8 unsigned integers!
    • Public network (Internet) - private network (LAN)
      • ABCD class address
      • 192.168.xx.xx, for internal use of the organization
  • Domain name: memory IP problem!
    • IP: www.vip.com
public static void main(String[] args) throws UnknownHostException {
        //Query local address
        InetAddress inetAddress1=InetAddress.getByName("127.0.0.1");
        System.out.println(inetAddress1);
        InetAddress inetAddress2=InetAddress.getLocalHost();
        System.out.println(inetAddress2);
        InetAddress inetAddress3=InetAddress.getByName("localhost");
        System.out.println(inetAddress3);
        //Query the ip address of the website
        InetAddress inetAddress4=InetAddress.getByName("www.baidu.com");
        System.out.println(inetAddress4);
        //Common methods
        //System.out.println(inetAddress4.getAddress());
        System.out.println(inetAddress4.getCanonicalHostName());
        System.out.println(inetAddress4.getHostAddress());//ip
        System.out.println(inetAddress4.getHostName());//Domain name, or the name of your own computer
    }

1.4 ports

A port represents the process of a program on a computer:

  • Different processes have different ports! Used to distinguish software
  • Specified 0-65535
  • TCP, UDP: 65535*2 tcp: 80, UDP: 80 port numbers cannot conflict under a single protocol
  • Port classification
    • Public port 0-1023
      • HTTP 80
      • HTTPS 443
      • FTP 21
      • Telent 23
    • Program registration port: 1024-49151, assign users or programs
      • Tomcat: 8080
      • Mysql: 3306
      • Oracle: 1521
    • Dynamic and private: 49152-65535
      netstat -ano #View all ports
      netstat -ano|findstr "5900" #View the specified port
      tasklist|findstr "8696" #View the process of the specified port
      
public class javaPractice {
    public static void main(String[] args) throws UnknownHostException {
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
        InetSocketAddress inetSocketAddress0 = new InetSocketAddress("localhost", 8080);
        System.out.println(inetSocketAddress);
        System.out.println(inetSocketAddress0);
        System.out.println(inetSocketAddress.getAddress());
        System.out.println(inetSocketAddress.getHostName());
        System.out.println(inetSocketAddress.getPort());
    }
}

1.5 communication protocol

Agreement: agreement, just as we speak Mandarin now

Network communication protocol: rate, transmission code rate, code structure, transmission control

Question: very complicated?

TCP/IP protocol cluster: it is actually a group of protocols

Important:

  • TCP: user transport protocol
  • UDP: User Datagram Protocol

Famous agreement:

  • TCP :
  • IP: network interconnection protocol

TCP UDP comparison:

  • Connection, stable
  • Three handshakes and four waves
    At least three times to ensure a stable connection!
    A: What are you looking at?
    B:What do you think?
    A:Do it!
    
    A:I am afraid that l have to go!
    B:Are you really leaving?
    B:Are you really leaving?
    A:I really have to go!
    
  • Client and server
  • The transmission is completed, the connection is released, and the efficiency is low
    UDP: send SMS
  • Not connected, unstable
  • Client, server: there is no clear boundary
  • It can be sent to you whether it is ready or not
  • Missile
  • DDOS: flood attack! (saturation attack)

1.6 TCP

client:
1. Connect to the server Socket
2. Send message

//client
public class javaPractice {
    public static void main(String[] args)  {
        Socket socket =null;
        OutputStream os =null;
        try {
            //1. Know the address and port number of the server
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port=9999;
            //2. Create a socket connection
             socket = new Socket(serverIP,port);
            //3. Send IO stream
             os = socket.getOutputStream();
            os.write("How do you do".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
           if(socket!=null){
               try {
                   socket.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
        }

    }
}

The server

  1. Establish service port ServerSocket
  2. Wait for user's link accept
  3. Accept user messages
//Server
public class TcpSeverDemo {
    public static void main(String[] args) {
        ServerSocket serverSocket =null;
        Socket socket=null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;
        try {
            //1. I have to have an address
             serverSocket = new ServerSocket(9999);
            while (true){
                //2. Wait for the client to connect
                 socket=serverSocket.accept();
                //3. Read the message from the client
                 is=socket.getInputStream();
                //Pipe flow
                 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) {
            e.printStackTrace();
        }finally {
            //close resource
            if(baos!=null){
                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(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

File upload

Server side

//Server
public class TcpSeverDemo {
    public static void main(String[] args) throws Exception {
        //1. Create service
        ServerSocket serverSocket = new ServerSocket(9000);
        //2. Listen for client links
        Socket socket=serverSocket.accept();//Blocking listening will always wait for the client
        //3. Get input stream
        InputStream is=socket.getInputStream();
        //4. Output of documents
        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);
        }
        //Notify the client that I have accepted it
        OutputStream os=socket.getOutputStream();
        os.write("I'm done. You can disconnect".getBytes());
        //close resource
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

client

//client
public class javaPractice {
    public static void main(String[] args) throws Exception {
        //1. Create a Socket connection
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
        //2 create an output stream
        OutputStream os=socket.getOutputStream();
        //3. Read the file
        FileInputStream fis=new FileInputStream(new File("tx.jpg"));
        //4. Write out documents
        byte[] buffer =new byte[1024];
        int len;
        while ((len=fis.read(buffer))!=-1){
            os.write(buffer,0,len);
        }
        //Notify the server that I'm finished
        socket.shutdownOutput();

        //Make sure that the server has received it before disconnecting the link
        InputStream inputStream=socket.getInputStream();
        //String byte[]
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        byte[] buffer2=new byte[1024];
        int len2;
        while ((len2=inputStream.read(buffer2))!=-1){
            baos.write(buffer2,0,len2);
        }
        System.out.println(baos.toString());
        //5. Close resources
        baos.toString();
        fis.close();
        os.close();
        socket.close();

    }
}

Tomcat

Server

  • Custom S
  • Tomcat server S: Java background development
    client
  • Custom C
  • Browser B

1.7 UDP

Texting: don't connect. You need to know the other party's address

send message

//No need to connect to the server
public class javaPractice {
    public static void main(String[] args) throws Exception {
        //1. Create a Socket
        DatagramSocket socket = new DatagramSocket();
        //2. Create a package
        String msg="Hello, server";
        //To whom
        InetAddress localhost=InetAddress.getByName("localhost");
        int port=9090;
        //Data, data length, start, end, to whom
        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
        //3. Send packet
        socket.send(packet);
        //4. Close flow
        socket.close();
    }
}

receive messages

public class TcpSeverDemo {
    public static void main(String[] args) throws Exception {
        //Open port
        DatagramSocket socket = new DatagramSocket(9090);
        //Accept packet
        byte[] buffer=new byte[1024];
        DatagramPacket packet=new DatagramPacket(buffer,0,buffer.length);
        socket.receive(packet);//Blocking acceptance
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        //Close connection
        socket.close();
    }
}

consulting service

  • Loop send message
public class javaPractice {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);
        //Prepare data: the console reads system in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true){
            String data=reader.readLine();
            byte[] datas= data.getBytes();
            DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));
            socket.send(packet);
            if(data.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}
  • Loop receive message
//Or do you want to wait for the client to connect
public class TcpSeverDemo {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);

        while(true){
            //Ready to accept the package
            byte[] container=new byte[1024];
            DatagramPacket packet = new DatagramPacket(container,0,container.length);
            socket.receive(packet);
            //Disconnect bye
            byte[] data=packet.getData();
            String receiveData=new String(data,0,data.length);
            System.out.println(receiveData);
            if(receiveData.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

Online consultation: both can be the sender or the receiver

  • Sender class
    //Sender
    public class javaPractice implements  Runnable{
        DatagramSocket socket =null;
        BufferedReader reader =null;
        private int fromPort;
        private String toIP;
        private int toPort;
        public javaPractice(int fromPort, String toIP, int toPort) {
            this.fromPort = fromPort;
            this.toIP = toIP;
            this.toPort = toPort;
            try{
                reader = new BufferedReader(new InputStreamReader(System.in));
                socket = new DatagramSocket(fromPort);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    
        @Override
        public void run() {
            while (true){
                try {
                    String data=reader.readLine();
                    byte[] datas= data.getBytes();
                    DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
                    socket.send(packet);
                    if(data.equals("bye")){
                        break;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            socket.close();
        }
    }
    
    
  • Class of receiving end
//Accept thread
public class TcpSeverDemo implements Runnable{
    DatagramSocket socket =null;
    private int port;
    private String msgFrom;
    public TcpSeverDemo(int port,String msgFrom) {
        this.port = port;
        this.msgFrom=msgFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(true){
            try {
                //Ready to accept the package
                byte[] container=new byte[1024];
                DatagramPacket packet = new DatagramPacket(container,0,container.length);
                socket.receive(packet);
                //Disconnect bye
                byte[] data=packet.getData();
                String receiveData=new String(data,0,data.length);
                System.out.println(msgFrom+"+"+receiveData);
                if(receiveData.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
  • Student multithreading
public class TalkStudent {
    public static void main(String[] args) {
        //Open two threads
        new Thread(new javaPractice(7777,"localhost",9989)).start();
        new Thread(new TcpSeverDemo(8877,"teacher")).start();
    }
}
  • Teacher multithreading
public class TalkTeacher {
    public static void main(String[] args) {
        //Open two threads
        new Thread(new javaPractice(5555,"localhost",8877)).start();
        new Thread(new TcpSeverDemo(9989,"student")).start();
    }
}

1.8 ,URL

https://www.baidu.com/
Uniform resource locator: to locate a resource on the Internet
DNS domain name resolution will be sent to www.baidu.com Com resolves to XXX xxx. xxx. xxx

agreement://ip address: port / project name / resource
  • URL class
public class javaPractice  {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloword/index.jsp?username=zhangqi&password=123546");
        System.out.println(url.getProtocol());//agreement
        System.out.println(url.getHost());  //Host IP
        System.out.println(url.getPort());  //port
        System.out.println(url.getPath());  //file
        System.out.println(url.getFile());  //Full path
        System.out.println(url.getQuery());  //parameter
    }
}

  • Internet File Download
public class javaPractice  {
    public static void main(String[] args) throws Exception {
        //Download address
        URL url = new URL("https://m801.music.126.net/20210518165914/a0fcdd2d4eba3014c00a1f548d299cd2/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/8617892023/21fe/6066/9da3/a3d134a4c7bf945e89601f6dd5cf7e08.m4a");
        //Connect resources
        HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
        InputStream inputStream=urlConnection.getInputStream();
        FileOutputStream fos=new FileOutputStream("8.m4a");
        byte[] buffer=new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);//Write this data
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();
    }
}

Keywords: Java network Network Communications

Added by FiveFlat on Wed, 09 Feb 2022 13:00:25 +0200