Java Simple UDP Communication example

Source: Internet
Author: User

Content: A simple example of UDP communication.

Receiver:

public class Receiver {public static void main (string[] args) {Datagramsocket ds = null;try {//udp Receive-side ds = new Datagramsock ET (8080);//defines where UDP packets are received byte[] buf = new byte[1024];//defines the data receive packet for UDP datagrampacket DP = new Datagrampacket (buf, Buf.length); while (true) {//Receive packet ds.receive (DP); String string = new String (Dp.getdata (), 0, Dp.getlength ()); System.out.println ("Length:" + dp.getlength () + "+" + string);}} catch (SocketException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally {if (ds = null) ds. Close ();}}}
Sender:

public class Sender {public static void main (string[] args) {Datagramsocket ds = null;try {///defines a UDP socket to send data ds = new D Atagramsocket (); String Hello = "Hello world";//defines a UDP data sending packet to send data, inetsocketaddress represents the address to receive datagrampacket DP = new Datagrampacket ( Hello.getbytes (), hello.getbytes (). Length, New inetsocketaddress ("127.0.0.1", 8080)); for (int i = 0; i <; i++) {DS.S End (DP); Thread.Sleep (1000);}} catch (Exception e) {e.printstacktrace ();} finally {if (ds! = null) Ds.close ();}}}



Java Simple UDP Communication example

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.