Texting: no need to connect, but you need to know the address of the other party, there is no clear boundary between client and server, and it can be said that there is no such thing as client and server.
transmitter
package lesson03; import ; import ; import ; /** * :: Transmitter */ public class UdpClientDemo1 { public static void main(String[] args) throws Exception { //Create a Socket DatagramSocket socket = new DatagramSocket(); /** * 2. Build a package */ //Messages to be sent String msg = "Hello, server!"; //Send address InetAddress localhost = ("localhost"); //Mainframe //Send port int port = 9090; /** * Five parameters: * @param buf (): the packet to be sent * @param offset 0: offset of the data * @param length ().length: length of the data * @param address localhost: destination address * @param port port: destination port */ DatagramPacket packet = new DatagramPacket((), 0, ().length, localhost, port); //3. Sending packages (packet); //4. Closing the stream (); } }
receiving end
package lesson03; import ; import ; /** * Receiver */ public class UdpServerDemo1 { public static void main(String[] args) throws Exception { // Open ports DatagramSocket socket = new DatagramSocket(9090); //Receive packets byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, 0, ); //Receive (packet); //blocking reception // Output packet address (().getHostAddress()); /** * Output packet data * packet: Data type * Converted to String type by constructor: new String(); */ (new String((), 0, ())); // Close the connection (); } }
The above is Java based on the UDP protocol to achieve the details of the message sent , more information about Java message sent to follow my other related articles !