java network programming

Keywords: Java udp

1. General

1. 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.

2. Purpose of network programming:

Dissemination and exchange of information, data exchange, communication

3. What is needed to achieve this effect:

  • How to accurately locate the host requires a port address and a resource of the computer
  • Find the host, how to transfer data?

4.javaweb: Web programming B/S

   Network programming: TCP/IP C/S

 
 

2. Network communication elements

Address of both parties:

  • ip
  • Port number

Rule: network communication protocol - TCP/IP

 
 

3. IP (uniquely locate a computer on a network)

1.IP class:

​ Class InetAddress

package 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 byName = InetAddress.getByName("127.0.0.1");
            //127.0.0.1: local localhost, local address
            InetAddress byName2 = InetAddress.getByName("localhost");
            InetAddress byName3 = InetAddress.getLocalHost();
            System.out.println(byName);
            System.out.println(byName2);
            System.out.println(byName3);
            
            //Query website IP address
            InetAddress byName1 = InetAddress.getByName("www.baidu.com");
            System.out.println(byName1);
            
            //common method
            System.out.println(byName1.getAddress());
            System.out.println(byName1.getCanonicalHostName());
            System.out.println(byName1.getHostAddress());
            System.out.println(byName1.getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

 

2.IP address classification

  • ipv4/ipv6:

    • ipv4: four bytes, 0 ~ 255, 4.2 billion: 3 billion are in North America and 400 million in Asia, which were exhausted in 2011.

    • 127.0.0.1

    • ipv6: 128 bits, 8 unsigned integers, abcde.

    • 2021:0bbb:34a6:222c:0000:7777:aaaa:0000

  • Public network (Internet) - private network (LAN):
      ABCD class address
      192.168,xx,xx / / for internal use

  • Domain name: memory IP problem

    IP: www.vip.com

 
 

4. Port

Port represents the process of a program on the computer; for example, IP is a building, and port is every family.

  • Different processes have different port numbers to distinguish software

  • 0 ~ 65535 ports are specified

  • Ports are divided into TCP,UDP: 65535 * 2. Port numbers under a single protocol cannot conflict. Two protocols can be, for example, tcp: 80, udp: 80.

  • Classification of ports:

    • Public port: 0 ~ 1023

      • HTTP : 80
      • HTTPS: 43
      • FTP : 21
      • Telent: 23
    • Program registration port: 1024 ~ 49151, distributed to users or programs

      • Tomcat: 8080
      • MySQL : 3306
      • Oracle : 1521
    • Dynamic, private port: 49152 ~ 65535

      netstat -ano    #View all ports
      netstat -ano|findstr "8884"  #View the specified port
      tasklist|findstr "7840"   
      

package IP;
import java.net.InetSocketAddress;
public class TestInetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
        System.out.println(inetSocketAddress);
    }
}

  
 

5. Communication protocol

1. Definitions

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

TCP/IP protocol cluster:

  • TCP: user transport protocol call: - connection - received - call
    • Connection, stable
    • Three handshakes and four waves
    • Client, server
    • The transmission is completed, the connection is released, and the efficiency is low
  • UDP: datagram protocol sending SMS: - sending is done - receiving
    • Not connected, unstable
    • Client, server: there is no clear boundary
    • You can send it whether you're ready or not
    • Missile
    • DDOS: flood attack (saturation attack)
  • IP: network interconnection protocol

 

2.TCP chat

client

package IP;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
//client
public class TcpClient {
    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 message IO stream
            os = socket.getOutputStream();
            os.write("Hello".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();
                }
            }
        }
    }
}

Server

package IP;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
//Server
public class TcpServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1. I have to have an address
             serverSocket= new ServerSocket(9999);
             //2. Wait for the client to connect
            accept = serverSocket.accept();
            //3. Read the message from the client
             is = accept.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 {
            if (baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (accept != null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!= null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

3.TCP file upload implementation

client

package IP;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClient1 {
    public static void main(String[] args) throws IOException {
        //Establish connection
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
        //Create an output stream
        OutputStream os = socket.getOutputStream();
        //read file
        FileInputStream fis = new FileInputStream(new File("Computer wallpaper 1.jpg"));
        //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();//I've transmitted it
         //Make sure that the server has received it before disconnecting
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer1 = new byte[1024];
        int len1 ;
        while ((len1 = fis.read(buffer1))!=-1){
            os.write(buffer1,0,len1);
        }
        System.out.println(baos.toString());
        
        //close resource
        baos.close();
        inputStream.close();
        os.close();
         fis.close();
        socket.close();
    }
}

Server

package IP;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer1 {
    public static void main(String[] args) throws IOException {
        //Create service
        ServerSocket serverSocket = new ServerSocket(9000);
        //Listen for client connections
        Socket socket = serverSocket.accept();//Blocking listening will wait for the client to connect
        //Get input stream
        InputStream is = socket.getInputStream();
        //File output
        FileOutputStream fos = new FileOutputStream(new File("sssss.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 received it
        OutputStream os = socket.getOutputStream();
        os.write("You can disconnect".getBytes());
        
        //close
        is.close();
        fos.close();
        socket.close();
        serverSocket.close();
    }
}

 

4.UDP message sending

You don't need to know each other's address

package IP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UdpClient {
    public static void main(String[] args) throws Exception {
        //1. Establish a connection Socket
        DatagramSocket socket = new DatagramSocket();
        //2. There is a bag
        String msg = "Hello";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        //3. Data, start of data length, to whom
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
        //4. Send packet
        socket.send(packet);
        //5. Close
        socket.close();
    }
}
package IP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpServer {
    public static void main(String[] args) throws Exception {
        //1. Open port
        DatagramSocket socket = new DatagramSocket(9090);
        //2. Receive packets
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet);//Blocking reception
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        socket.close();
    }
}

 

5.UDP chat implementation

consulting service

package IP;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class UdpSender {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);
        //Preparing data; console reading
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true){
            String data = reader.readLine();
            byte[] datas = data.getBytes();//The data is not readable, so it is converted to bytes
            DatagramPacket packet = new DatagramPacket(datas,0,data.length(),new InetSocketAddress("localhost",6666));
            socket.send(packet);
            if (datas.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}
package IP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpReceive {
    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();
    }
}

 

6.UDP multithreading

package IP;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
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() {
        //Preparing data; console reading
        while (true){
            String data = null;
            try {
                data = reader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] datas = data.getBytes();//The data is not readable, so it is converted to bytes
            DatagramPacket packet = new DatagramPacket(datas,0,data.length(),new InetSocketAddress(this.toIP,this.toPort));
            try {
                socket.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (datas.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}
package IP;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReveice implements Runnable{
    DatagramSocket socket = null;
    private int port;
    private String msgFrom;
    public TalkReveice(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){
            //Ready to accept the package
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container,0,container.length);
            try {
                socket.receive(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //Disconnect bye
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, data.length);
            System.out.println(msgFrom+":"+receiveData);
            if (receiveData.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}
package IP;
public class TalkStudent {
    public static void main(String[] args) {
        //Open two threads
        new Thread(new TalkSend(5555,"localhost",9999)).start();
        new Thread(new TalkReveice(9999,"student")).start();
    }
}
package IP;
public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(7777,"localhost",8888)).start();
        new Thread(new TalkReveice(8888,"teacher")).start();
    }
}

 
 

6.Tomcat

The server

  • Custom S
  • Tomcat server S, java background development

client

  • Custom C
  • Browser B

 
 

7.URL

1. Definitions

https://www.baidu.com/

Uniform resource locator: used to locate a resource on the Internet

DNS: domain name resolution www.baidu.com xxx.xx.xx

agreement://ip address: port number / project name / resource
package IP;
import java.net.MalformedURLException;
import java.net.URL;
public class Url {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=xiao&password=123");
        System.out.println(url.getProtocol());//Protocol name
        System.out.println(url.getHost());//Host ip
        System.out.println(url.getPath());//File path
        System.out.println(url.getFile());//Full path
        System.out.println(url.getPort());//port
        System.out.println(url.getQuery());//parameter
    }
}

 

2.URL Download Network Resources

package IP;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class UrlDown {
    public static void main(String[] args) throws IOException {
        //1. Download address
        URL url = new URL("http://p1.music.126.net/cHdqyvyO3Zr7yV67gTPr1A==/109951166422718066.jpg?imageView&quality=89");
        //2. Connect to this resource HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("4.jpg");
        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();
    }
}

Posted by dannyb785 on Mon, 20 Sep 2021 05:44:58 -0700