Java network programming

1,IP

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

//Test IP
public class TestInetAddress {
    public static void main(String[] args) {
        try {
            //Query local address
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress1);
            InetAddress inetAddress2 = InetAddress.getByName("localhost");
            System.out.println(inetAddress2);
            InetAddress inetAddress3 = InetAddress.getLocalHost();
            System.out.println(inetAddress3);

            //Query website address
            InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress4);

            //common method
            //System.out.println(inetAddress4.getAddress());
            System.out.println(inetAddress4.getCanonicalHostName());//Canonical name
            System.out.println(inetAddress4.getHostAddress());//ip
            System.out.println(inetAddress4.getHostName());//Domain name or computer name
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }
}

2. Port

A port represents a computer's process

Different processes have different port numbers.

The specified port number range is 0 ~ 65535 (each protocol), tcp (0 ~ 65535) and udp (0 ~ 65535), with a total of 65525 * 2

The port numbers written individually cannot be the same. The port numbers between different protocols are repeated.

Port classification:

  • Public port: 0 ~ 1023               Try not to use it
  • HTTP: 80
  • HTTPS: 443
  • FTP: 21
  • Telent: 23
  • Program registration port: 1024 ~ 49151, assigned to users or programs.
  • Tomcat: 8080
  • MySQL: 3306
  • Oracle: 1521
  • Dynamic and private: 49152 ~ 65525       Try not to use it

Common operations:

netstat -ano #View all ports
netstat -ano | findstr "5900" #View the specified port
tasklist/findstr "8696" #View processes on the specified port
ctr1+ shift + ESC  #Shortcut key to open Task Manager
import java.net.InetSocketAddress;

//socket
public class TestInetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress socketAddress1 = new InetSocketAddress("127.0.0.1", 8080);
        InetSocketAddress socketAddress2 = new InetSocketAddress("localhost", 8080);
        System.out.println(socketAddress1);
        System.out.println(socketAddress2);

        System.out.println(socketAddress2.getAddress());
        System.out.println(socketAddress2.getHostName());//address
        System.out.println(socketAddress2.getPort());//port
    }
}

3. Communication protocol

Agreement: agreement, just as we speak Mandarin now.
Network communication protocol: rate, transmission code, i code structure, transmission control... Problem: very complex?
Make things small: layered!
TCP/IP protocol cluster: it is actually a group of protocols.

Important:
TCP: user transport protocol. UDP: user datagram protocol.

Main agreements:
TCP: user transport protocol.   IP: network interconnection protocol.

TCP and UDP

TCP:

  • Connection and stability
  • Three handshakes and four waves
  • Client and server
  • Transmission completed, connection released, low efficiency

UDP:

  • Disconnected and unstable
  • Client and server: there is no clear interface
  • Direct transmission
  • Like a missile attack
  • DDOS: flood attack (saturation attack): forcibly sending a large number of garbage packets and blocking the network.

4,TCP

client  :

  1. Connect to the server Socket
  2. send message
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

//Client 01
public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os =null;
        try {
            //1. You need to know the address and port number of the server
            InetAddress serverIp = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            //2. Establish Socket connection
            socket = new Socket(serverIp, port);
            //3. Send message IO stream
            os = socket.getOutputStream();
            os.write("Hello, online world".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 customer link accept
  3. Accept message
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//The server
public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket =null;
        Socket socket =null;
        InputStream is =null;
        ByteArrayOutputStream baos =null;
        try {
            //1. An address is required
            serverSocket = new ServerSocket(9999);
            //2. Waiting for customer connection
            while (true) {
                socket = serverSocket.accept();
                //3. Read client messages
                is = socket.getInputStream();
            /*
            byte[] buffer=new byte[1024];
            int len;
            while ((len=is.read(buffer))!=-1){
                String msg = new String(buffer, 0, len);
                System.out.println(msg);
            }
            */
                //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

client

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClientDemo02 {
    public static void main(String[] args) throws Exception {
        //1. Establish connection
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
        //2. Create output stream
        OutputStream os = socket.getOutputStream();
        //3. Read file
        FileInputStream fis = new FileInputStream("up.png");
        //4. Write file
        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();

        //Confirm that the server has received the data before disconnecting
        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);
        }
        System.out.println(baos.toString());

        //5. Close resource
        baos.close();
        inputStream.close();
        fis.close();
        os.close();
        socket.close();
    }
}

The server

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

public class TcpServerDemo02 {
    public static void main(String[] args) throws Exception {
        //Create service port
        ServerSocket serverSocket = new ServerSocket(9000);
        //Waiting for connection
        Socket socket = serverSocket.accept();
        //get data
        InputStream is = socket.getInputStream();
        //output file
        FileOutputStream fos = new FileOutputStream(new File("receive.png"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len= is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }

        //Tell the client that I have received it
        OutputStream os = socket.getOutputStream();
        os.write("I've received it. I can't disconnect it".getBytes());

        //close resource
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();

    }
}

Tomcat

The server:

  • Custom S
  • Tomcat S

client:

  • Custom C
  • Browser B

UDP

Similar to texting, you don't need to connect. You need to know the other party's address

Sender

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

//No connection required
public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        //1. Create a Socket
        DatagramSocket socket = new DatagramSocket();
        //2. Create a package
        String msg = "Hello,Word!";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        // Data, starting from the length of the data, to whom
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
        //3. Send packet
        socket.send(packet);
        //Close flow
        socket.close();
    }
}

receiving end

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

public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
        //Open port
        DatagramSocket socket = new DatagramSocket(9090);
        //Receive packet
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

        socket.receive(packet);

        System.out.println(packet.getAddress().getHostName());
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        //Close connection
        socket.close();
    }
}

Circular transmission

Sender:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class UpdateSenderDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);

        //Preparing data: console reading, 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();
    }
}

Receiving end:

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

public class UpdateReceiverDemo01 {
    public static void main(String[] args)throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);

        while (true) {
            //Ready to accept package
            byte[] container = new byte[1024];

            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            socket.receive(packet);//Blocking acceptance

            //bye disconnect
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, packet.getLength());
            System.out.println(receiveData);

            if (receiveData.equals("bye")) break;
        }
        socket.close();


    }
}

Simple chat (meeting dialogue)

TalkSend

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class TalkSend implements Runnable   {
    DatagramSocket socket = null;
    BufferedReader reader =null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        }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();
    }
}

TaklReceive

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

public class TalkReceive implements Runnable{
    DatagramSocket socket =null;
    private int port;
    private String msgFrom;

    public TalkReceive(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 package
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);//Blocking acceptance

                //bye disconnect
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, packet.getLength());
                System.out.println(this.msgFrom+":"+receiveData);

                if (receiveData.equals("bye")) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

TalkStudent

public class TalkStudent {
    public static void main(String[] args) {
        //Open two threads
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkReceive(8888,"teacher")).start();
    }
}

TalkTeacher

public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(5555,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"student")).start();
    }
}

URL (uniform resource locator: locate a resource and a resource on the Internet)

agreement://ip address: port / project / resource

URL common methods

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

public class URLDemo01 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://www.baodu.com:8080/helloword/index.jsp?username=yao&password=123");
        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 address
        System.out.println(url.getFile());//File full path
        System.out.println(url.getQuery());//parameter
    }
}

Download network resources using URL

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

public class URLDown {
    public static void main(String[] args) throws Exception {
        //Download address
        URL url = new URL("https://m701.music.126.net/20211124231827/4b608a1bc8ebd9c0293443c48c4e2c9c/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/11624482968/5b8b/9912/7c40/3877aa1c480cedeb274dae1b816efbb6.m4a");
        //Connect to this resource
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("a.m4a");
        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        System.out.println("Download complete");

        fos.close();
        inputStream.close();
        urlConnection.disconnect();
    }
}

Tags: Java Back-end

Posted on Wed, 24 Nov 2021 13:51:50 -0500 by jaypotter