Broadcast of Java datagram programming

Source: Internet
Author: User
Tags constructor final sendfile sleep thread
Programming | data

UDP broadcasts, which are actually very simple, understand IP address scheme, understand what is broadcast, many articles called multicast, I think that is called broadcasting is better, because multicast is to broadcast and multicast refers to the generic, in the Java program to deal with nature is different, this article and the next article is only to emphasize the concept.

As mentioned above, the broadcast address includes a directed broadcast address and a limited broadcast address, the TCP/IP protocol stipulates that these two addresses can only appear on the local network, the router executes this rule, does not forward the destination address for broadcast address messages to other networks, and multicast is different, the next introduction multicast programming.

This broadcast program can be a broadcast program simply by modifying the destination address of the message in the unicast program into a broadcast address.

Package recmail.multiservice;

Import Java.net.DatagramSocket;
Import java.net.*;
Import java.io.*;
Import java.util.ArrayList;
Import Java.util.Iterator;

public class Datagramrecvsender_b extends Dataswaplisteneradapter
Implements Runnable {
public static final int datagramport = 10698;
Private Java.net.DatagramSocket Road;
Private InetAddress IA;
Datagrampacket DP;
public static final int datagram_length = 8192;
Private Datapacket CDP;
Private Boolean ishandling = true;

Dataswapevent dsevent;
/**
* This constructor is used to receive datagrams.
*/
Public Datagramrecvsender_b () {
try {
System.out.println ("recv ...");
Dsevent = new Dataswapevent (this);
SocketAddress sa = new Inetsocketaddress (
Datagramrecvsender_b.datagramport);
At a minimum, you specify the datagram receive port, which is the only requirement on the receiving end. Of course, if the host is a multiple access host, you need to road = new Datagramsocket (SA);
Road = new Datagramsocket (datagramrecvsender_b.datagramport);
System.out.println (Road.isbound () + "::" +road.getbroadcast ());
}
catch (SocketException ex) {
Ex.printstacktrace ();
}
catch (Exception Ex1) {
Ex1.printstacktrace ();
}
}
/**
* This constructor is used to send datagrams.
* @param send String
*/
Public Datagramrecvsender_b (String send) {
try {
SYSTEM.OUT.PRINTLN ("Send ...");
This class can compute the directed broadcast address of the local network.
BROADCASTADDR info = new Broadcastaddr ();
Info.setnetmask ("255.255.255.0");
INFO.SETNETADDR ("192.168.0.106");
Info.execcalc ();
ia = Inetaddress.getbyname (info.getnetbroadcastaddr ());//"255.255.255.255"
Dsevent = new Dataswapevent (this);
SocketAddress sa = new Inetsocketaddress (IA,
Datagramrecvsender_b.datagramport);
If you need to receive datagrams, you need to specify a port, otherwise you do not have to specify. Road = new Datagramsocket (datagramrecvsender_s.datagramport-1);
Road = new Datagramsocket ();
The Getbroadcast () of the Datagramsocket class instance returns True, that is, the Broadcast property default setting for the class is true or enabled.
Road.setbroadcast (TRUE); You can test what happens when Road.setbroadcast (false) is executed.
System.out.println ("isbound--" +road.isbound () + ": getbroadcast--" +road.getbroadcast ());
}
catch (SocketException ex) {
Ex.printstacktrace ();
}
catch (Unknownhostexception Ex1) {
Ex1.printstacktrace ();
}
}

public void SendFile (String file) {
CDP = new Datapacket (file);
System.out.println (file);
Iterator it = cdp.getdatapackets (). iterator ();
Byte[] B;
while (It.hasnext ()) {
B = ((DataEntry) It.next ()). GetByte ();
Datagrampacket DP = new Datagrampacket (b, 0, b.length, ia,datagramrecvsender_b.datagramport);
try {
Thread.Sleep (100);
if (dp==null)
Continue
Road.send (DP);
}
catch (Exception ex) {
Ex.printstacktrace ();
}
}
}

public Boolean ishandling () {
return ishandling;
}

public void Ishandling (Boolean ishand) {
ishandling = Ishand;
}

public void Run () {
byte[] buffer = new Byte[datapacket.dataswapsize];
Datagrampacket packet = new Datagrampacket (buffer, buffer.length);
Datapacket DP = new Datapacket ();
while (ishandling) {
Packet.setlength (buffer.length);
System.out.println ("wait;");
try {
Road.receive (packet);
Dp. ADD (Packet.getdata ());
if (Dp.isfull ()) {
Dsevent.setimage (DP. Gereratedata ());
This.processrecvfinishedevent (dsevent);
DP = new Datapacket ();
}
}
catch (IOException ex) {
System.out.println (ex);
}
}
}

  public static void main (string[] args) {
    String file[];
    ArrayList al = new ArrayList ();
   //Replace the image folder on your machine
    String path = "e:\\nature\\";
    File f = new file (path);
    file = F.list ();
    Datagramrecvsender_b Dgrs = new Datagramrecvsender_b ("");
    for (int j=0;j<1000;j++)
    for (int i = 0; i < file.length; i++) {
&nbs p;     try {
        thread.sleep;
     }
      catch (Interruptedexception ex) {
      }
      if (file[i].endswith ("jpg") | | file[i].endswith ("BMP")
        dgrs.sendfile (path + file[i]);
   }
 }
}

public static void Main (string[] args) {
String file[];
ArrayList al = new ArrayList ();
String Path = "e:\\nature\\"; Nature Mzip
File F = new file (path);
File = F.list ();
Datagramrecvsender_b Dgrs = new Datagramrecvsender_b ("");
for (int j=0;j<1000;j++)
for (int i = 0; i < file.length; i++) {
try {
Thread.Sleep (2000);
}
catch (Interruptedexception ex) {
}
if (File[i].endswith ("jpg") | | file[i].endswith ("BMP")
System.out.println (File[i]);
Al.add (path + file[i]);
Dgrs.sendfile (path + file[i]);
}
}
}

The receiving end displays the same interface as the unicast, and only one sentence is modified:

In the main method of class testdual, change the datagramrecvsender_s to Datagramrecvsender_b, put the receiver on several machines on your local area network, and you should see the images that are constantly displayed.

public static void Main (string[] args) {
Testdual test = new testdual ();
Test.initmain ();
Test.go ();
datagramrecvsender_s Dgrs = new datagramrecvsender_s ();
Dgrs.adddataswaplistener (test);
Thread thread = new Thread (DGRS, "test");
Thread.Start ();
}

The next article introduces multicast programming.



Related Article

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.