Java Network Programming-UDP

Source: Internet
Author: User

Java Network Programming-UDP

Client code first

Package com.test.net; import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetAddress; public class UDPClient {/*** UDP client */public static void main (String [] args) throws Exception {DatagramSocket socket = new DatagramSocket (); string str = "hello"; byte [] buf = str. getBytes (); DatagramPacket packet = new DatagramPacket (buf, buf. length, InetAddress. getByName ("127.0.0.1"), 1111);/* send packets directly */socket. send (packet );}}

Server code

Package com.test.net; import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetAddress; import java.net. socketException; public class UDPServer {/*** UDP server */public static void main (String [] args) throws Exception {DatagramSocket socket = new DatagramSocket (1111 ); byte [] buf = new byte [256]; DatagramPacket packet = new DatagramPacket (buf, buf. length);/* listener, blocking */socket. receive (packet); String received = new String (packet. getData (); System. out. println (received );}}

First, let's talk about UDP. UDP is a non-connection protocol. Simply put, it is a one-way transmission. You do not need to establish a connection in advance, nor need to return packets. Therefore, you only need an IP address and port, and UDP can send packets to this port. If there is any such IP address or port, or the other party does not receive the packets, UDP will not work. Therefore, the most important thing in UDP is the two classes. One is mongoramsocket and the other is mongorampacket. The first class is similar to socket, and the second class is UDP packet.

On the server, the receive method of mongorampacket is blocked, which is equivalent to listening until the datagram is listened.

Output result



The result is that the server outputs hello.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.