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:
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:
|
<<: JavaScript array deduplication solution
>>: The difference between two MySQL delete user statements (delete user and drop user)
Table of contents Nginx proxies two socket.io ser...
explain is used to obtain query execution plan in...
This article shares the installation steps of MyS...
This article shares the specific code of JavaScri...
Table of contents The browser's rendering mec...
Original address: https://blog.csdn.net/m0_465798...
Table of contents 1. Merge interface 1.1 Non-func...
When using vue to develop projects, the front end...
Preface ActiveMQ is the most popular and powerful...
<br /> English original: http://desktoppub.a...
How to change the MySQL database directory locati...
Mac comes with Apache environment Open Terminal a...
1. Effect display An astronaut watch face written...
Overview es6 adds a new way to get specified elem...
XML files should be encoded in utf-8 as much as p...