UDP Broadcast Java

Source: Internet
Author: User

1. Service Side

 Public classUdpbroadcastserver {/**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        intPort = 9999;//Open the Listening portDatagramsocket ds =NULL; Datagrampacket DP=NULL; byte[] buf =New byte[1024];//store the messages that are sent        Try {            //of the bound portDS =NewDatagramsocket (port); DP=NewDatagrampacket (buf, buf.length); System.out.println ("Listen for broadcast port open:");  while(true) {ds.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 broadcast message:" +sbuf.tostring ()); Try{Thread.Sleep (1000); }                Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        }        Catch(SocketException e) {e.printstacktrace (); }        Catch(IOException e) {e.printstacktrace (); }    }}

2, the Client

 Public classudpbroadcastclient {/**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method Stub//Broadcast implementation: broadcast by the client, server-side receiveString host = "255.255.255.255";//Broadcast Address        intPort = 9999;//destination port for broadcastString message = "Test";//the string to send        Try{inetaddress adds=Inetaddress.getbyname (host); Datagramsocket DS=NewDatagramsocket (); Datagrampacket DP=NewDatagrampacket (Message.getbytes (), message.length (), adds, port);  while(true) {Ds.send (DP); Try{Thread.Sleep (1000); }                Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        }        Catch(unknownhostexception e) {e.printstacktrace (); }        Catch(SocketException e) {e.printstacktrace (); }        Catch(IOException e) {e.printstacktrace (); }    }}

UDP Broadcast 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.