UDP Multicast Java

Source: Internet
Author: User

1. Service Side

 Public classUdpmulticastserver {/**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method Stub//The datagram service, which accepts multicast and sends multicast, adds the multicast address.String host = "225.0.0.1";//Multicast address        intPort = 9998; intLength = 1024; byte[] buf =New byte[length]; MulticastSocket Ms=NULL; Datagrampacket DP=NULL; Try{ms=NewMulticastSocket (port); DP=Newdatagrampacket (buf, length); //join A multicast addressInetAddress Group =Inetaddress.getbyname (host);            Ms.joingroup (group); System.out.println ("Listen for multicast port open:");  while(true) {ms.receive (DP); inti; StringBuffer Sbuf=NewStringBuffer ();  for(i = 0; i < 1024x768; i++) {                    if(Buf[i] = = 0) {                         Break; } sbuf.append ((Char) buf[i]); } System.out.println ("Received multicast message:" +sbuf.tostring ()); Try{Thread.Sleep (1000); }                Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        }        Catch(IOException e) {e.printstacktrace (); }    }}

2, the Client

 Public classudpmulticastclient {/**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method StubString host = "225.0.0.1";//Multicast address        intPort = 9998; String message= "Test-multicastsocket"; Try{inetaddress Group=Inetaddress.getbyname (host); MulticastSocket s=NewMulticastSocket (); //join a multicast groupS.joingroup (group); Datagrampacket DP=NewDatagrampacket (Message.getbytes (), Message.length (), group, port);  while(true) {S.send (DP); Try{Thread.Sleep (1000); }                Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        }        Catch(unknownhostexception e) {e.printstacktrace (); }        Catch(IOException e) {e.printstacktrace (); }    }}

UDP Multicast Java

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.