Network programming, WebSocket Foundation

Network programming, WebSocket Foundation

  1. summary:
  • Network globalization connects the world through the network.

  • Connect through domain name (ip address) and port number.

  • Real time interaction: when making a call, the technology used is TCP connection.

  • Transmit information: send information. UDP connection is used.

  • 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:

    Communication, data exchange.

  • What is needed to achieve the desired effect:

    If you accurately locate other machines (IP address), ports and a resource on this computer on the network;

    Find this host, if transferring data, (Media: Hardware)

  • Java Web page programming, B/S architecture

  • Network programming: TCP/IP C/S architecture

  1. Elements of network communication
  • If network communication is realized: it is necessary to know the address (IP) and port of both sides of the communication;

  • Network communication protocol:

  • Summary:

    • In network programming:
      • How to accurately locate one or more hosts that need to be connected on the network;
      • How to communicate after finding the host;
    • Elements in network programming:
      • Ip and port number;
      • Network communication protocol; TCP,UDP
    • Everything is object
  1. Why is IP used in java
  • ip address: InetAddress (encapsulated jar)

    • Uniquely locate a computer on a network;

    • IP Classification: IPV4/IPV6, public / private network

      IPV4: xxx. xxx. xxx. XXX consists of 4 bytes.

      IPV6: 128 bits, 8 unsigned integers.

  • Domain name: ip name, easy to remember.

InetAddress.getXXX//Get some needed information 
  1. A port that represents a program process on a computer
  • Different processes have different port numbers, which will not conflict, and the same port cannot run at the same time;
  • Port range: 0 ~ 65535, tcp default: 80, udp 8080
  • Public port: 0 – 1023, http default: 80, https default: 443, FTP: 21
  • Program registration port, try to use 1024 – 49151.
//understand
InetSocketAddress isa = InetSocketAddress("127.0.0.1",8080);
isa.getAddress  getHostName
  1. Communication protocol: agreement.
  • Network communication protocol, very complex, no need to learn;

  • TCP/IP protocol: it is actually a group of protocols, among which the most important is

    • TCP: user transport protocol
    • UDP: User Datagram Protocol
    • IP: network interconnection protocol
  • TCP UDP comparison

    • TCP: call

      Connection, stability, three handshakes, four waves

      //Ensure stable connection at least three times
      A: Do you miss me?
      B: Are you drinking too much?
      A: Oh, I wipe.
      //Disconnecting requires a minimum of four interactions
      A: Expenses!
      B: How much did you spend?
      B: Everyone's spending?
      A: Well, expenses.
      

      Client and server

      Transmission completed, connection released, low efficiency

    • UDP: send SMS

      Not connected, unstable

      Client and server: there is no clear boundary

      It can be sent to you whether it is ready or not.

      DDOS: flood attack.

  1. TCP information transmission (basic method)
  • The client connects to the server Socket and transmits information through the stream
//client
public class TcpClient {
    public static void main(String[] args) {
        try{
            //1. Get the server address and port
            InetAddress ia = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            //2. Create a socket connection
            Socket socket = new Socket(ia,port);
            //Write data to the output stream and send messages
            OutputStream os = socket.getOutputStream();
            os.write("The weather is good. Go to the field".getBytes());

            os.close();
            socket.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
  • The server side establishes an open port on the server side, accept s the waiting information, receives the data through the input stream, reads the data stream into the output stream, and then reads the content in toString mode.
//Server (after startup, only wait for one time to receive information)
public class TcpServer {
    public static void main(String[] args) {
        try {
            //1. One of my addresses and ports
            ServerSocket serverSocket = new ServerSocket(9999);
            //2. Wait for the client to connect
            Socket accept = serverSocket.accept();
            //3. Read message
            InputStream is = accept.getInputStream();

            /** There is a problem of Chinese garbled code in this writing
            byte[] bytes = new byte[1024];
            int line = -1;
            while((line = is.read(bytes)) != -1){
                String ss = new String(bytes,0,line);
                System.out.println(ss);
            }
             */
            ByteArrayOutputStream bais = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int line = -1;
            while((line = is.read(bytes)) != -1){
                bais.write(bytes,0,line);
            }
            System.out.println(bais.toString());

            //To close the flow, it is best to define it outside of try. Use finally to close the flow and judge whether it is empty
            bais.close();
            is.close();
            accept.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//Server (waiting to receive information)
public class TcpServer {
    public static void main(String[] args) {
        Socket accept = null;
        InputStream is = null;
        ByteArrayOutputStream bais = null;
        ServerSocket serverSocket = null;
        try {
            //1. One of my addresses and ports
            serverSocket = new ServerSocket(9999);
            while(true){
                //2. Wait for the client to connect
                accept = serverSocket.accept();
                //3. Read message
                is = accept.getInputStream();
                bais = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int line = -1;
                while((line = is.read(bytes)) != -1){
                    bais.write(bytes,0,line);
                }
                System.out.println(bais.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //To close the flow, it is best to define it outside of try. Use finally to close the flow and judge whether it is empty
            try {
                bais.close();
                is.close();
                accept.close();
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  1. Picture upload
//Receiving file -- server side
public class TcpClientDemo22 {
    public static void main(String[] args) throws IOException {
        //Create a server listening port
        ServerSocket serverSocket = new ServerSocket(9000);
        //Blocking monitoring client connection, waiting all the time, and the monitoring is over
        Socket accept = serverSocket.accept();
        //Receive incoming information from client
        InputStream inputStream = accept.getInputStream();
        //File output
        FileOutputStream fileOutputStream = new FileOutputStream(new File("2.jpg"));
        byte[] bytes = new byte[1024];
        int line = -1;
        while((line=inputStream.read(bytes))!=-1){
            fileOutputStream.write(bytes,0,line);
        }
        //Notification client received
        OutputStream os = accept.getOutputStream();
        os.write("I'm finished".getBytes());
        //close resource
        os.close();
        fileOutputStream.close();
        inputStream.close();
        accept.close();
        serverSocket.close();
    }
}
//Read files and send messages ----- client
public class TcpClientDemo2 {
    public static void main(String[] args) throws IOException {
        //Create a Socket connection
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
        //Create an output stream
        OutputStream os = socket.getOutputStream();
        //Get file stream read file
        FileInputStream fis = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\1.3 Han Wantong-hs\\1.jpg"));
        //Write file
        byte[] bytes = new byte[1024];
        int line = -1;
        while((line = fis.read(bytes))!=-1){
            os.write(bytes,0,line);
        }
        //After the incoming is completed, you should notify the server that I have finished the transmission
        socket.shutdownOutput();
        //Confirm that the server has received the returned information and disconnect
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream byteArrayInputStream = new ByteArrayOutputStream();
        byte[] bytes1 = new byte[1024];
        int line1 = -1;
        while((line1=inputStream.read(bytes1))!=-1){
            byteArrayInputStream.write(bytes1,0,line1);
        }
        System.out.println(byteArrayInputStream.toString());
        //close resource
        byteArrayInputStream.close();
        inputStream.close();
        os.close();
        fis.close();
        socket.close();
    }
}
  1. Tomcat knows

    Tomcat starts Chinese garbled code and modifies logging. In the conf folder The properties file UTF-8 is changed to GBK;

    Only one port can be enabled under the same protocol

  1. UDP message sending: do not connect, but need to know the other party's address;
//You don't need to connect to the server, just send it out (you can also listen to 8090 to receive information when sending mail, but it's not processed here)
public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception{
        //Create a Socket
        DatagramSocket socket = new DatagramSocket(8090);
        //Build a package, make and send information
        String msg = "Let's go out and fight in the field";
        InetAddress ip = InetAddress.getByName("localhost");
        int prot = 9090;
        DatagramPacket dp = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,ip,prot);
        //Send packet
        socket.send(dp);
        //close resource
        socket.close();
    }
}
//The server can receive information or send information
public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
        //Development port receiving data
        DatagramSocket socket = new DatagramSocket(9090);
        //Receive sent datagram
        byte[] bytes = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);
        //Blocking reception
        socket.receive(datagramPacket);
        System.out.println(datagramPacket.getAddress());
        System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
        //close resource
        socket.close();
    }
}
  1. UDP chat: one end circularly sends messages and the other end circularly receives messages
//Loop send message
public class UdpSender {
    public static void main(String[] args) throws Exception {
        //Create a listening port
        DatagramSocket socket = new DatagramSocket(9001);
        //Create a data table and the data to be sent
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//Input information
        while(true){
            //Read data
            String readLine = br.readLine();
            System.out.println("Send out:" + readLine);
            byte[] bytes = readLine.getBytes();
            //Create input packet
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, InetAddress.getByName("localhost"), 9002);
            //Send packet
            socket.send(packet);
            if("goodbye".equals(readLine.trim())){
                System.out.println("Close the client.");
                break;
            }
        }
        //close resource
        br.close();
        socket.close();
    }
}
//Loop receive message
public class UdpReceive {
    public static void main(String[] args) throws Exception{
        //Create a listening port
        DatagramSocket socket = new DatagramSocket(9002);
        while(true){
            //Receive packet
            byte[] bytes = new byte[1024];
            DatagramPacket getData = new DatagramPacket(bytes, 0, bytes.length);
            socket.receive(getData);//Blocking receiving information
            //Get the received information and translate it
            byte[] data = getData.getData();
            String datas = new String(data,0,data.length);
            System.out.println("Received:" + datas);
            if("goodbye".equals(datas.trim())){
                System.out.println("Close the server.");
                break;
            }
        }
        socket.close();
    }
}
  1. Multithreaded UDP online chat can be sent and received at both ends
//Online chat send message
public class TalkSend implements Runnable{
    DatagramSocket socket = null;
    BufferedReader bufferedReader = 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);
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        while(true){
            try{
                String buffer = bufferedReader.readLine();
                byte[] datas = buffer.getBytes();
                DatagramPacket packet = new DatagramPacket(datas,0,datas.length, new InetSocketAddress(this.toIp,this.toPort));
                socket.send(packet);
                if("goodbye".equals(buffer.trim())){
                    break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
//Online chat receiving messages
public class TalkReceive implements Runnable{
    DatagramSocket socket = null;
    private int port;
    private String name;
    public TalkReceive(int port,String name) {
        this.port = port;
        this.name = name;
        try {
            socket = new DatagramSocket(port);
        }catch (SocketException e){
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        while(true){
            try {
                //Ready to receive package
                byte[] bytes = new byte[1024];
                DatagramPacket datagramSocket = new DatagramPacket(bytes,0,bytes.length);
                socket.receive(datagramSocket);//Blocking receiving package

                byte[] data = datagramSocket.getData();
                String datas = new String(data,0,data.length);
                System.out.println(this.name + ": " + datas);

                if("goodbye".equals(datas.trim())){
                    System.out.println("Close the server.");
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
//Enable chat thread user 1
public class TalkStartO1 {
    public static void main(String[] args) {
        //Open two threads
        //TalkSend localhost1 = new TalkSend(7001, "localhost", 7002);
        //TalkReceive localhost2 = new TalkReceive(7001, "woman");
        new Thread(new TalkSend(17004, "localhost", 17002)).start();
        new Thread(new TalkReceive(17001, "woman")).start();
    }
}
//Enable chat thread user 2
public class TalkStartO2 {
    public static void main(String[] args) {
        //Open two threads
        TalkSend localhost1 = new TalkSend(17003, "localhost", 17001);
        TalkReceive localhost2 = new TalkReceive(17002, "man");
        new Thread(localhost1).start();
        new Thread(localhost2).start();
    }
}
  1. URL to download network resources
  • Unified resource locator, locating resources, locating a resource on the Internet.

    Protocol: / / ip address: port / project name / resource

//Download network resources according to network address
public class UrlFileDown {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://i2.hdslb.com/bfs/face/83bb511365da513c55aa3d1958524f3b7db40684.jpg");
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("3.jpg");
        byte[] bytes = new byte[1024];
        int line;
        while((line = inputStream.read(bytes))!=-1){
            fos.write(bytes,0,line);
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();//Close connection
    }
}

Learning source, crazy God Theory Click to enter

Keywords: Java

Added by Toboe on Thu, 03 Mar 2022 13:33:49 +0200