UDP connection object principle analysis and usage examples

UDP connection object principle analysis and usage examples

I wrote a simple UDP server and client example before to get started with UDP, but a problem occurred when I actually used it!

Last time I used it, I also wrote the connection object DatagramSocket as static and used it when the class was initialized. However, it is used in many places in the system. Do I have to keep creating objects of this class?

You can do this, but there are consequences, and the consequence is memory overflow.

UDP is stateless. DatagramSocket only needs to be created once to start pointing to a port at a certain address without having to be created each time.

Since UDP is stateless, when you create a DatagramSocket object, you only create an object pointing to the network, just like you set up a big speaker facing a certain direction, but you don't know if there is anyone listening in this direction.

Even if you don't have a server running, there is no problem creating a connection object and sending data to this address. It’s nothing if you shout in a certain direction with a loudspeaker and no one listens! But if you don't receive a response when you need one, an error will be reported after a timeout!

package udp; 
 
import java.net.*; 
 
/** 
 * @Description UDP client program, used to send data to the server and receive the server's response information* @author cuisuqiang 
 * @version 1.0 
 * @since <a href="mailto:[email protected]" rel="external nofollow" >[email protected]</a> 
 */ 
public class UdpClientSocket { 
  /** 
   * Connection object */ 
  private static DatagramSocket ds = null; 
  /** 
   * Address object */ 
  private static SocketAddress address = null; 
   
  /** 
   * Test the client's method of sending packets and receiving response information*/ 
  public static void main(String[] args) throws Exception { 
    init(); 
    while(true){ 
      UdpClientSocket.send(address,"Hello, dear!".getBytes()); 
      UdpClientSocket.receive(); 
      try { 
        Thread.sleep(3 * 1000); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 
  } 
   
  /** 
   * Initialize the connection and address */ 
  public static void init(){ 
    try { 
      ds = new DatagramSocket(8899); // Bind to local port as client ds.setSoTimeout(2 * 1000); 
      address = new InetSocketAddress("127.0.0.1",3344); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
  } 
   
  /** 
   * Send data information to the specified server */ 
  public static void send(SocketAddress address,byte[] bytes){ 
    try { 
      DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address); 
      ds.send(dp); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
  } 
 
  /** 
   * Receive data sent back from the specified server*/ 
  public static void receive(){ 
    try { 
      byte[] buffer = new byte[1024]; 
      DatagramPacket dp = new DatagramPacket(buffer, buffer.length); 
      ds.receive(dp);    
      byte[] data = new byte[dp.getLength()]; 
      System.arraycopy(dp.getData(), 0, data, 0, dp.getLength());  
      System.out.println("Server response data: " + new String(data)); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
  } 
}

The results of executing the code are as follows:

java.net.SocketTimeoutException: Receive timed out
at java.net.PlainDatagramSocketImpl.receive0(Native Method)
at java.net.PlainDatagramSocketImpl.receive(PlainDatagramSocketImpl.java:136)
at java.net.DatagramSocket.receive(DatagramSocket.java:712)
at udp.UdpClientSocket.receive(UdpClientSocket.java:69)
at udp.UdpClientSocket.main(UdpClientSocket.java:28)

The operation timed out, but the error was not caused by creating objects and sending data, but by a timeout when receiving data!

This program keeps running, let's make a server:

package udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * @Description of UDP service class * @author cuisuqiang
 * @version 1.0
 * @since [email protected]
 */
public class UdpServerSocket {
	
	private static DatagramSocket ds = null;
	private static SocketAddress address = null;
	
	/**
	 * Test method */
	public static void main(String[] args) throws Exception {
		init();
		System.out.println("---->Service starts listening!<----");
		while (true) {
			UdpServerSocket.receive();
			UdpServerSocket.response(address,"Hello, have you eaten?");
		}		
	}
	
	public static void init(){
		try {
			ds = new DatagramSocket(3344);
			ds.setSoTimeout(0);
			address = new InetSocketAddress("127.0.0.1",8899);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Receive data packets. This method will cause thread blocking */
	public static void receive() {
		try {
			byte[] buffer = new byte[1024];
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			ds.receive(packet);
			String info = new String(packet.getData(), 0, packet.getLength());
			System.out.println("Receive information: " + info);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Send the response packet to the requester */
	public static void response(SocketAddress address,String info){
		try {
			DatagramPacket dp = new DatagramPacket(info.getBytes(), info.getBytes().length, address);
			dp.setData(info.getBytes());
			ds.send(dp);
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
}

After running, the client can send and receive data normally!

If in actual use, I set a system startup item to initialize the init connection object and address, and then capture the exception when using it!

If your connection object is created every time and used frequently, the system will usually crash in a few minutes!

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • UDP simple server client code example
  • Detailed explanation of Python UDP programming
  • C# Sample code using TCP/UDP protocol
  • Java network based on UDP chat program example analysis
  • Java simulated UDP communication sample code
  • Python implements UDP program communication process diagram
  • Python implements file transfer under UDP protocol
  • Java UDP communication client and server example analysis

<<:  JavaScript array deduplication solution

>>:  The difference between two MySQL delete user statements (delete user and drop user)

Recommend

Detailed explanation of the pitfalls of nginx proxy socket.io service

Table of contents Nginx proxies two socket.io ser...

MySQL explain obtains query instruction information principle and example

explain is used to obtain query execution plan in...

MySQL 5.7.17 Compressed Version Installation Notes

This article shares the installation steps of MyS...

JavaScript implements draggable modal box

This article shares the specific code of JavaScri...

MySQL 8.0.20 installation tutorial and detailed tutorial on installation issues

Original address: https://blog.csdn.net/m0_465798...

The most common declaration merge in TS (interface merge)

Table of contents 1. Merge interface 1.1 Non-func...

How to use Dayjs to calculate common dates in Vue

When using vue to develop projects, the front end...

Docker learning method steps to build ActiveMQ message service

Preface ActiveMQ is the most popular and powerful...

The grid is your layout plan for the page

<br /> English original: http://desktoppub.a...

How to change the MySQL database directory location under Linux (CentOS) system

How to change the MySQL database directory locati...

Using Apache ab to perform http performance testing

Mac comes with Apache environment Open Terminal a...

Let's talk about destructuring in JS ES6

Overview es6 adds a new way to get specified elem...

Web front-end development experience summary

XML files should be encoded in utf-8 as much as p...