Java Network Programming TCP/UDP (Socket)

Network programming

1.1 overview

Purpose:

  • Dissemination and exchange of information, data exchange and communication

What you want to achieve:

  1. How to accurately locate a host on the network: ip:port locate a resource on this machine
  2. Found this host, how to transfer data

javaweb: Web programming B/S

Network programming: TCP/IP C/S

1.2 elements of network communication

How to realize network communication?

Address of both parties:

  • ip
  • port

Rules: protocols for network communication

TCP/IP reference model:

Summary:

  1. Two main problems in network programming
    1. How to accurately locate the host on the network
    2. How to communicate after finding
  2. Elements in network programming
    1. IP and port number
    2. Network communication protocol TCP, UDP
  3. Everything is object

1.3,IP

ip address: InetAdress

  • Uniquely locate a computer on a network
  • 127.0.0.1 local localhost
  • Classification of IP addresses
    • ipv4 / ipv6
      • IPV4: 127.0.0.1, 4 bytes, 0-255
      • IPV6: 128 bit. 8 unsigned integers
    • Public network (Internet) - private network (LAN)
      • ABCD class address
    • Domain name: memory IP problem!
    public static void main(String[] args) throws UnknownHostException {
        InetAddress byName = InetAddress.getByName("127.0.0.1");
        System.out.println(byName);
        InetAddress inetAddress = InetAddress.getByName("www.baidu.com");
        System.out.println(inetAddress.getCanonicalHostName());//Get specification name
        System.out.println(inetAddress.getAddress());//Address is an array
        System.out.println(inetAddress.getHostName());//Get domain name
    }

1.4 port

A port represents a program on a computer

  • Different processes have different ports to distinguish software
  • Port specification (0-65535)
  • TCP, UDP: the same protocol port cannot conflict
  • Port classification
    • Public port 0 ~ 1023
      • HTTP: 80
      • HTTPS: 443
      • FTP: 21
      • Telnet: 23
    • Program registration port: 1024 ~ 49151, assign users or programs
      • Tomcat: 8080
      • Mysql: 3306
      • Oracle: 1521
    • Dynamic and private: 49152 ~ 65535
      • cmd viewing port: netstat -ano | findstr "3306"
      • tasklist|findstr "pid" view the specified program
        InetSocketAddress address1 = new InetSocketAddress("127.0.0.1", 8080);

        InetSocketAddress address2 = new InetSocketAddress("localhost", 8080);
        System.out.println(address1);
        System.out.println(address2);
        System.out.println(address1.getAddress());
        System.out.println(address1.getHostName());//address
        System.out.println(address1.getPort());//port

1.5 communication protocol

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

TCP/IP protocol is a group of protocols

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

Famous agreement:

  • TCP
  • IP: network interconnection protocol
TCP UDP comparison

TCP: call

  • Connection, stable
  • Three handshakes and four waves
  • Client and server
  • The transmission is completed, the connection is released, and the efficiency is low

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

1.6 TCP

client

  1. Empty server Socket
  2. Send message

The server

  1. Establish the port of the service
  2. Wait for the user's connection accept
//client
public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket =null;
        OutputStream outputStream =null;
        //1. Know the server address
        try {
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            //2 port number
            int port = 9999;
            //3 create a socket connection
            socket = new Socket(ip,port);
            //4 send message
            outputStream = socket.getOutputStream();
            outputStream.write("Hello".getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

//The server
public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket =null;
        InputStream inputStream =null;
        ByteArrayOutputStream bos = null;
        //1 have an address
        try {
            serverSocket = new ServerSocket(9999);
            //2 wait for the client to connect
            socket = serverSocket.accept();
            //3. Read the message from the client
            inputStream = socket.getInputStream();
            //Pipe flow
            bos = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len;
            while ((len = inputStream.read(buff))!=-1){
                bos.write(buff,0,len);
            }
            System.out.println(buff.toString());


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //close resource
            if (bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.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();
                }

            }
        }
    }
}

1.7 UDP

Texting: just send

send message

public class UdpClientDemo1 {
    //Sender
    public static void main(String[] args) throws Exception {
        //Create a Socket
        DatagramSocket socket = new DatagramSocket();
        //Build a package
        String msg = "Oriental saseno";
        //To whom
        InetAddress address = InetAddress.getByName("localhost");
        int port = 9090;
        DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes("UTF-8"),0,msg.getBytes().length,address,port);

        //Send packet

        socket.send(datagramPacket);
        socket.close();
    }
}

public class UdpserverDemo1 {
    //receiving end
    public static void main(String[] args) throws IOException {
        //Open port
        DatagramSocket socket   = new DatagramSocket(9090);
        //Receive DataPacket
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet);
        System.out.println(packet.getAddress().getHostAddress());
        byte[] data = packet.getData();
        System.out.println(new String(data,0, packet.getLength(),"UTF-8"));
        socket.close();
    }
}

1.8 URL

Download files via url

    public static void main(String[] args) throws Exception {
        //setup connection
        URL url = new URL("https://www.xxx.com/xxx.gif");
        //Connection url
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //download
        InputStream inputStream = connection.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File("xxx.gif"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        fos.close();
        inputStream.close();
        connection.disconnect();
    }

Send messages to each other

//send out
public class RunSender implements Runnable{
    DatagramSocket socket = null;
    private int fromPort;
    private String toHostName;
    private int toPort;

    public RunSender(int fromPort,int toPort,String toHostName) {
        this.fromPort = fromPort;
        this.toPort = toPort;
        this.toHostName = toHostName;
        try {
            socket = new DatagramSocket (fromPort);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                String data = null;
                data = reader.readLine();
                byte[] datas = data.getBytes("UTF-8");
                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(toHostName, toPort));
                socket.send(packet);
                if (data.equals("bye")){
                    socket.close();
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }
}

//receive
public class RunReceive implements Runnable{
    private int rcPort;
    DatagramSocket socket = null;

    public RunReceive(int rcPort) {
        this.rcPort = rcPort;
        try {
            socket = new DatagramSocket(rcPort);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            try {
                byte[] bytes = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
                socket.receive(packet);
                byte[] data=  packet.getData();
                String datas = new String(data, 0, packet.getLength(), "UTF-8");
                System.out.println(socket.getLocalPort()+":"+datas);
                if (datas.equals("bye")){
                    socket.close();
                    break;

                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}


    public static void main(String[] args) {
        new Thread(new RunSender(7777,8888,"localhost")).start();
        new Thread(new RunReceive(9999)).start();
    }

    public static void main(String[] args) {
        new Thread(new RunSender(6666,9999,"localhost")).start();
        new Thread(new RunReceive(8888)).start();
    }

Tags: Java network udp

Posted on Fri, 03 Dec 2021 17:20:00 -0500 by collamack