Java Network Programming (UDP programming)

Source: Internet
Author: User

Client


Package org.udp;



Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;


public class UdpClient {
public static void Main (string[] args) throws exception{
Datagramsocket ds = null;
byte[] buf = new byte[2014];
Datagrampacket DP = NULL;
ds = new Datagramsocket (9000);
DP = new Datagrampacket (buf,1024);
System.out.println ("Waiting to receive data. ");
Ds.receive (DP);
String str = new String (Dp.getdata (), 0,dp.getlength ()) + "from"
+dp.getaddress (). Gethostaddress () + ":" +dp.getport ();
System.out.println (str);
Ds.close ();
}

}


Program Run Result: wait to receive data.


Server-side


Package org.udp;


Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;


public class Udpserver {
public static void Main (string[] args) throws exception{
Datagramsocket ds = null;
Datagrampacket DP = NULL;
ds = new Datagramsocket (3000);
String str = "Hello word";
DP = new Datagrampacket (Str.getbytes (), Str.length (), Inetaddress.getbyname ("localhost"), 9000);
SYSTEM.OUT.PRINTLN ("Send message. ");
Ds.send (DP);
Ds.close ();
}
}


Program Run Result: send message.






The client can accept the information sent from the server side, the client program running result: waiting to receive data.
Hello wordfrom127.0.0.1:3000

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.