Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What is the principle of java UDP communication?

Shulou Source: shulou.com Published: 2022-05-31 10:47:58 09月11日 Update

This article introduces the relevant knowledge of "what is the principle of java UDP communication". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Principle

1. UDP protocol is an unreliable network protocol, which establishes a Socket object at each end of the communication, but these two Socket are just objects that send and receive data.

2. For both sides of the communication based on UDP protocol, there is no so-called client-side and server-side concept.

Java provides DatagramSocket classes as Socket based on UDP protocol

Example

Package test; import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress; / * * UDPCLient deom * @ author * / public class UDPClient {public static void main (String [] args) throws Exception {DatagramSocket clientSocket = new DatagramSocket (); BufferedReader inFromUser = new BufferedReader (new InputStreamReader (System.in)) / / get the local IP address InetAddress IPAddress = InetAddress.getLocalHost (); byte [] sendData; byte [] receiveData = new byte [1024]; System.out.println ("Please enter an English sentence and the server will return its uppercase form (enter exit to exit)"); while (true) {String sentence = inFromUser.readLine () If (sentence.equals ("exit")) break; sendData = sentence.getBytes (); / / create a send Datagram packet with source address #, destination address # DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, IPAddress, 9876); / / send Datagram packet clientSocket.send (sendPacket) / / create a receive Datagram packet DatagramPacket receivePacket = new DatagramPacket (receiveData, receiveData.length); / / receive the Datagram packet clientSocket.receive (receivePacket) of the receiving server; String modifiedSentence = new String (receivePacket.getData ()); System.out.println ("FROM SERVER:" + modifiedSentence);} clientSocket.close () This is the end of the content of "what is the principle of java UDP communication". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Data communication principle address server service content object more knowledge input utility learning and then two both ends both sides just dilemma uppercase. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Redmi Shulou Information vpn Docker