Network programming: UDP and TCP send and receive data, and TCP upload client files to the server

Posted by fuzzy1 on Sat, 29 Jan 2022 10:17:52 +0100

1. Three elements of network programming

Network programming refers to the program running on different computers under the network communication protocol, which can carry out data transmission

1.1 IP address

IP address: it is the unique identification of the device in the network

IP addresses fall into two categories:

IPv4: assign a 32bit address to each host connected to the network. For example, an IP address in binary form is "11000000 10101000 00000001 01000010". For convenience, the IP address is often written in decimal form with the symbol "." Separate different bytes. Therefore, the above IP address can be expressed as "192.168.1.66".

IPv6: due to the vigorous development of the Internet, in order to expand the address space, redefine the address space through IPv6, adopt 128 bit address length, each 16 bit group is divided into 8 groups of hexadecimal numbers, which solves the problem of insufficient network address resources.

Special IP address: 127.0.0.1 is the loopback address, which can represent the local address. It is generally used for testing

InetAddress: this class represents an Internet Protocol (IP) address

Relevant methods:

Method nameexplain
static InetAddress getByName(String host)Determine the IP address of the host name. The host name can be either a machine name or an IP address
String getHostName()Gets the host name of this IP address
String getHostAddress()Returns the IP address string in the text display
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Demo01 {
    public static void main(String[] args) throws UnknownHostException {
        //Gets the native InetAddress object
        InetAddress ia = InetAddress.getByName("172.20.0.15");
        //Get the string form of the local IP address
        String hostAddress = ia.getHostAddress();
        //Get the name of this machine
        String hostName = ia.getHostName();
        
        System.out.println(hostAddress);
        System.out.println(hostName);
    }
}

1.2 ports and protocols

Port: the unique identification of the application on the device

Port number: an integer represented by two bytes. Its value range is 0 ~ 65535. Among them, the port number between 0 and 1023 is used for some well-known network services and applications. Ordinary applications need to use a port number of more than 1024. If the port number is occupied by another service or application, the current program will fail to start

Protocol: in computer network, the rules of connection and communication are called network communication protocol

UDP protocol: user datagram protocol is a connectionless communication protocol, that is, during data transmission, the sender and receiver of data do not establish a logical connection.

TCP protocol: transmission control protocol is a connection oriented communication protocol, that is, before transmitting data, establish a logical connection between the sending end and the receiving end, and then transmit data. It provides reliable and error free data transmission between two computers.

2. UDP communication program

2.1 UDP sending data

UDP communication in Java

  • UDP protocol is an unreliable network protocol. It establishes a Socket object at both ends of the communication, but these two sockets are only the objects to send and receive data. Therefore, for both sides of communication based on UDP protocol, there is no so-called concept of client and server
  • Java provides DatagramSocket class as a Socket based on UDP protocol

Construction method:

Method nameexplain
DatagramSocket()Create a datagram socket and bind it to any available port on the native address
DatagramPacket(byte[] buf,int len,InetAddress add,int port)Create a packet and send a packet with a length of len to the specified port of the specified host

To send data

  • Create a Socket object (datagram Socket) at the sending end
  • Create data and package it
  • Call the send method of DatagramSocket object to send data
  • Close sender
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpSend {
    public static void main(String[] args) {
        DatagramSocket ds = null;
        try {
            //Create a DatagramSocket object to send data
            ds = new DatagramSocket();
            String str = "udp transmission";
            byte[] bytes = str.getBytes();
            int len = bytes.length;
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            //Package the data to be sent with datagram packet object
            DatagramPacket dp = new DatagramPacket(bytes, len, inetAddress, 10000);
            //Send data. The parameter is packed data
            ds.send(dp);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ds !=null){
                //Close sender
                ds.close();
            }
        }

    }
}

2.2 UDP receiving data

Steps to receive data

  • Create a Socket object (datagram Socket) at the receiving end
  • Create a packet to receive data
  • Call the method of DatagramSocket object to receive data
  • Analyze the data package and display the data on the console
  • Close the receiver
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpRecive {
    public static void main(String[] args) {
        DatagramSocket ds = null;
        try {
            //DatagramSocket object is used to receive data, and the port needs to be specified
            ds = new DatagramSocket(10000);
            byte[] bytes = new byte[1024];
            int len = bytes.length;
            //Create an empty packet to receive data
            DatagramPacket dp = new DatagramPacket(bytes, len);
            //Receive data with packet as parameter
            ds.receive(dp);
            //Parse packet
            byte[] data = dp.getData();
            int length = dp.getLength();
            System.out.println(new String(data, 0, length));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ds != null){
                ds.close();
            }
        }
    }
}

2.3 three communication modes of UDP

  • Unicast: unicast is used for end-to-end communication between two hosts
  • Multicast: multicast is used to communicate with a specific group of hosts
  • Broadcast: broadcast is used for data communication between one host and all hosts on the whole LAN

Multicast:

// Sender
public class ClinetDemo {
    public static void main(String[] args) throws IOException {
        // 1. Create the Socket object (DatagramSocket) of the sender
        DatagramSocket ds = new DatagramSocket();
        String s = "hello Multicast ";
        byte[] bytes = s.getBytes();
        InetAddress address = InetAddress.getByName("224.0.1.0");
        int port = 10000;
        // 2. Create data and package the data (datagram packet)
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length,address,port);
        // 3. Call the method of DatagramSocket object to send data (in unicast, it is sent to the computer with the specified IP, but in multicast, it is sent to the multicast address)
        ds.send(dp);
        // 4. Release resources
        ds.close();
    }
}
// receiving end
public class ServerDemo {
    public static void main(String[] args) throws IOException {
        // 1. Create a receiver Socket object (MulticastSocket)
        MulticastSocket ms = new MulticastSocket(10000);
        // 2. Create a box to receive data
        DatagramPacket dp = new DatagramPacket(new byte[1024],1024);
        // 3. Bind the current computer to a multicast address to add it to this group
        ms.joinGroup(InetAddress.getByName("224.0.1.0"));
        // 4. Receive the data into the box
        ms.receive(dp);
        // 5. Analyze the data package and print the data
        byte[] data = dp.getData();
        int length = dp.getLength();
        System.out.println(new String(data,0,length));
        // 6. Release resources
        ms.close();
    }
}

radio broadcast:

// Sender
public class ClientDemo {
    public static void main(String[] args) throws IOException {
      	// 1. Create a sending Socket object (DatagramSocket)
        DatagramSocket ds = new DatagramSocket();
		// 2. Create a box for storing data and encapsulate the broadcast address
        String s = "radio broadcast hello";
        byte[] bytes = s.getBytes();
        InetAddress address = InetAddress.getByName("255.255.255.255");
        int port = 10000;
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length,address,port);
		// 3. Send data
        ds.send(dp);
		// 4. Release resources
        ds.close();
    }
}
// receiving end
public class ServerDemo {
    public static void main(String[] args) throws IOException {
        // 1. Create the Socket object (DatagramSocket) of the receiving end
        DatagramSocket ds = new DatagramSocket(10000);
        // 2. Create a packet for receiving data
        DatagramPacket dp = new DatagramPacket(new byte[1024],1024);
        // 3. Call the method of DatagramSocket object to receive data
        ds.receive(dp);
        // 4. Analyze the data package and display the data on the console
        byte[] data = dp.getData();
        int length = dp.getLength();
        System.out.println(new String(data,0,length));
        // 5. Close the receiver
        ds.close();
    }
}

3. TCP communication program

TCP communication in Java

  • Java provides a good package for the network based on TCP protocol, uses Socket object to represent the communication ports at both ends, and generates IO flow through Socket for network communication.
  • Java provides a Socket class for the client and a ServerSocket class for the server

send out:

public class ClientDemo {
    public static void main(String[] args) throws IOException {
        //Create the client's Socket object (Socket)
        //Socket(String host, int port) creates a stream socket and connects it to the specified port number on the specified host
        Socket s = new Socket("127.0.0.1",10000);

        //Get output stream and write data
        //OutputStream getOutputStream() returns the output stream of this socket
        OutputStream os = s.getOutputStream();
        os.write("hello,tcp,I'm coming.".getBytes());

        //Release resources
        s.close();
    }
}

receive:

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        //Create a server-side Socket object (ServerSocket)
        //ServerSocket(int port) creates a server socket bound to a specified port
        ServerSocket ss = new ServerSocket(10000);

        //Socket accept() listens for the socket to be connected to and accepts it
        Socket s = ss.accept();

        //Get the input stream, read the data, and display the data on the console
        InputStream is = s.getInputStream();
        byte[] bys = new byte[1024];
        int len = is.read(bys);
        String data = new String(bys,0,len);
        System.out.println("The data are:" + data);

        //Release resources
        s.close();
        ss.close();
    }
}

matters needing attention:

  • The accept method is blocked. Its function is to wait for the client to connect
  • The client creates an object and connects to the server. At this time, the connection with the server is guaranteed through the three-time handshake protocol
  • For the client, it is written out, so it is an output stream; For the server, it reads in, so it is an input stream
  • The read method is also blocked
  • When the client closes the stream, it also has an action to write an end tag to the server. If there is no end tag, the server reading will not stop
  • The last step is to disconnect and ensure the termination of the connection through the four wave protocol

4. File upload via TCP

Case requirements

Client: data comes from local files and receives server feedback

Server: write the received data into the local file and give feedback

client:

import java.io.*;
import java.net.Socket;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 10086);

        //bis is the byte buffered input stream of local files, which is used to read the files to be uploaded
        FileInputStream fs = new FileInputStream("day11_exercise\\05.jpg");
        BufferedInputStream bis = new BufferedInputStream(fs);
        //os is the output stream in the network and transmits files to the server
        OutputStream os = socket.getOutputStream();
        //Upload file
        int b;
        while ((b = bis.read()) != -1) {
            os.write(b);
        }
        socket.shutdownOutput();//Close the output stream of socket and write an end flag to the stream

        //The feedback from the receiving server is in Chinese. The conversion stream, the stream obtained from the incoming socket and the specified encoding format need to be used
        InputStream socketInputStream = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(socketInputStream,"gbk");
        BufferedReader br = new BufferedReader(isr);
        String str;
        while ((str = br.readLine())!=null){
            System.out.print(str);
        }
        br.close();
        socket.close();
        bis.close();
    }
}

The server:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
//The server will receive files and save them locally. The function is realized by multithreading, and the files uploaded by multiple clients can be stored at the same time
//The run method in Runnable is rewritten here, and the thread pool can also be used to reduce the overhead of opening up multiple threads
public class Service {
    public static void main(String[] args) throws IOException {
        //File receiving network stream
        ServerSocket ss = new ServerSocket(10086);
        while (true) {
            Socket accept = ss.accept();
            SocketThread st = new SocketThread(accept);
            Thread thread = new Thread(st);
            thread.start();
        }
//        ss.close();
    }
}
import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class SocketThread implements Runnable {
    private Socket accept;

    public SocketThread(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        BufferedWriter bw = null;

        try {
            //Get the network stream and read it in
            InputStream is = accept.getInputStream();
            //The local output stream is written locally
            FileOutputStream fs = new FileOutputStream("day15_exercise\\" + UUID.randomUUID().toString() + ".jpg");
            bos = new BufferedOutputStream(fs);

            //Write to server local
            int b;
            while ((b = is.read()) != -1) {
                bos.write(b);
            }

            System.out.println("Feedback to customers");
            OutputStream socketos = accept.getOutputStream();
            bw = new BufferedWriter(new OutputStreamWriter(socketos,"gbk"));
            bw.write("Upload succeeded!");
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

If there is any error, please leave a comment and correct it in time. June 18, 2021

 

Topics: Java socket Multithreading JavaSE