The first is the code of TCP’s client
//1. Create a client Socket and specify the server address and port Socket socket = new Socket("localhost",8888); //2. Obtain the output stream and send information to the server side OutputStream os = socket.getOutputStream(); //byte output stream PrintWriter pw = new PrintWriter(os); //Wrap output stream as print stream Pw.write ("username: admin; Password: 453 "); pw.flush(); //Refresh cache and output to server side socket.shutdownOutput();
Then the code of the UDP client
//1. Define the address, port number and data of the server InetAddress address = InetAddress.getByName("localhost"); int port=8000; Byte data = "username: admin; Password: 123".getBytes (); //2. Create a datagram containing the data information sent DatagramPacket packet=new DatagramPacket(data,data.length,address,port); //3. Create DatagramSocket Object DatagramSocket socket =new DatagramSocket(); //4. Send Datagram to Server socket.send(packet);
The client here sends some data to the local server. What I cannot understand is why TCP is so complicated. Get the output stream, wrap the print stream, and refresh the cache once. In contrast, UDP is so simple.
Why is this?
I think it may be a matter of agreement. It seems that the foundation has to be supplemented recently.
Because TCP is based on flow, while UDP is based on message.