Java UDP network programming-simple example

Source: Internet
Author: User

  1. /**
  2. * Udpserver
  3. * @ Author Winty wintys@gmail.com
  4. * @ Version 2008-12-15
  5. */
  6. Import java. Io .*;
  7. Import java.net .*;
  8. Class udpserver {
  9. Public static void main (string [] ARGs) throws ioexception {
  10. Datagramsocket Server = new datagramsocket (5050 );
  11. Byte [] recvbuf = new byte [1, 100];
  12. Datagrampacket recvpacket
  13. = New datagrampacket (recvbuf, recvbuf. Length );
  14. Server. Receive (recvpacket );
  15. String recvstr = new string (recvpacket. getdata (), 0, recvpacket. getlength ());
  16. System. Out. println ("Hello world! "+ Recvstr );
  17. Int Port = recvpacket. getport ();
  18. Inetaddress ADDR = recvpacket. getaddress ();
  19. String sendstr = "Hello! I'm server ";
  20. Byte [] sendbuf;
  21. Sendbuf = sendstr. getbytes ();
  22. Datagrampacket sendpacket
  23. = New datagrampacket (sendbuf, sendbuf. length, ADDR, Port );
  24. Server. Send (sendpacket );
  25. Server. Close ();
  26. }
  27. }

  1. /**
  2. * Udpclient
  3. * @ Author Winty wintys@gmail.com
  4. * @ Version 2008-12-15
  5. */
  6. Import java. Io .*;
  7. Import java.net .*;
  8. Class udpclient {
  9. Public static void main (string [] ARGs) throws ioexception {
  10. Datagramsocket client = new datagramsocket ();
  11. String sendstr = "Hello! I'm client ";
  12. Byte [] sendbuf;
  13. Sendbuf = sendstr. getbytes ();
  14. Inetaddress ADDR = inetaddress. getbyname ("127.0.0.1 ");
  15. Int Port = 5050;
  16. Datagrampacket sendpacket
  17. = New datagrampacket (sendbuf, sendbuf. length, ADDR, Port );
  18. Client. Send (sendpacket );
  19. Byte [] recvbuf = new byte [1, 100];
  20. Datagrampacket recvpacket
  21. = New datagrampacket (recvbuf, recvbuf. Length );
  22. Client. Receive (recvpacket );
  23. String recvstr = new string (recvpacket. getdata (), 0, recvpacket. getlength ());
  24. System. Out. println ("Received:" + recvstr );
  25. Client. Close ();
  26. }
  27. }

Attachment: source program

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.