Java network programming

Posted by Kestrad on Fri, 31 Dec 2021 12:22:13 +0100

What is network programming?

Baidu Encyclopedia: network programming, in a big way, is the function of sending and receiving information, and the intermediate transmission is the physical line. The main work of network programming is to assemble the information package through the specified protocol at the sending end, and analyze the package according to the specified protocol at the receiving end, so as to extract the corresponding information and achieve the purpose of communication.

Three elements of network programming

  • IP: used to find addresses and communicate with each other
  • Port: used to find our application. For example, the data sent by wechat can only be received by wechat
  • Protocol: the protocol used for communication and data transmission. The common protocols are TCP and UDP

UDP communication

User packet protocol, the sender only sends data, regardless of whether the receiver can receive it or not, but it is efficient. It is often used for unsafe data transmission but needs fast transmission

Steps for sending data from the sender:

  • Create sender object DatagramSocket()
  • Package data
  • send data
  • Close sender resources
//Create sender object
DatagramSocket ds=new DatagramSocket();

byte[] b="886".getBytes();
//The sender must specify parameters: data, data length, to which host and which port
DatagramPacket dp=new DatagramPacket(b,b.length,InetAddress.getByName(null),8080);

//send data
ds.send(dp)

//close resource
ds.close()

Steps for receiving data at the receiving end:

  • Create receiving end object DatagramSocket(port)
  • receive data
  • Parsing packets
  • close resource
//Create receiver object
DatagramSocket ds=new DatagramSocket(8080);

//Create a packet to receive data
byte[] b=new byte[1024];
DatagramPacket dp=new DatagramPacket(b,b.length);

//receive data 
ds.receive(dp);

//Parsing packets
byte[] data=dp.getData();
String s=new String(data, 0, dp.getLength());
System.out.println(s);

Network transmission from keyboard input
Sender

//Sender
public class A {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds=new DatagramSocket();

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line=br.readLine())!=null){
            if(line.equals("886")){
                DatagramPacket dp=new DatagramPacket("886".getBytes(),"886".getBytes().length,InetAddress.getByName(null),8080);
                ds.send(dp);

                ds.close();
                System.out.println("End of sending");
                break;
            }
            DatagramPacket dp=new DatagramPacket(line.getBytes(),line.getBytes().length,InetAddress.getByName(null),8080);
            ds.send(dp);
        }
    }
}

receiving end

//receiving end
public class B {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException, InstantiationException {
        DatagramSocket ds=new DatagramSocket(8080);

        while(true){
            byte[] b=new byte[1024];
            DatagramPacket dp=new DatagramPacket(b,b.length);

            ds.receive(dp);

            byte[] data=dp.getData();
            if(new String(data, 0, dp.getLength()).equals("886")){
                System.out.println("End of reception");
                break;
            }
            System.out.println(new String(data, 0, dp.getLength()));
        }

        ds.close();
    }
}

TCP communication

The transmission control protocol establishes a Socket object at both ends of the communication. There will be a three-time handshake before the connection, and a four-time disconnection at the end, but it is inefficient and suitable for safe data transmission.
Steps for sending data from the sender:

  • Create the sender Socket object
  • Get output stream
  • Send data
  • Close sender object

It should be noted that if the sender wants to send data, the receiver must be turned on first, because there are three handshakes

//Sender
public class A {
    public static void main(String[] args) throws IOException {
        Socket ss=new Socket("127.0.0.1",8080);

        OutputStream outputStream = ss.getOutputStream();

        outputStream.write("hello".getBytes());

        ss.close();
    }
}

Steps for receiving data at the receiving end:

  • Create the receiver ServerSocket object
  • Monitor sender
  • Get input stream
  • receive data
  • Close receiver object
public class B {
    public static void main(String[] args) throws IOException {
        ServerSocket ss=new ServerSocket(8080);

        Socket sss = ss.accept();

        InputStream inputStream = sss.getInputStream();

        byte[] b=new byte[1024];
        int len=inputStream.read(b);
        String str=new String(b,0,len);
        System.out.println(str);
    }
}

Send files from one host to another
Sender

public class A {
    public static void main(String[] args) throws IOException {
        Socket ss=new Socket("127.0.0.1",8080);

        BufferedReader br=new BufferedReader(new FileReader("data.txt"));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(ss.getOutputStream()));

        String line;
        while((line=br.readLine())!=null){
            bw.write(line);
            bw.flush();
            bw.newLine();
        }

        ss.close();
    }
}

receiving end

public class B {
    public static void main(String[] args) throws IOException {
        ServerSocket ss=new ServerSocket(8080);

        Socket sss = ss.accept();

        BufferedReader br=new BufferedReader(new InputStreamReader(sss.getInputStream()));
        BufferedWriter bw=new BufferedWriter(new FileWriter("date.txt"));

        String line;
        while((line=br.readLine())!=null){
            bw.write(line);
            bw.flush();
            bw.newLine();
        }

        ss.close();
    }
}

Topics: Java network udp