The multicast of Java datagram programming

Source: Internet
Author: User
Tags interface join net range sleep string thread tostring
Programming | data

In the information age, the application of network technology has been very common. Many of these applications rely on the ability to send the same information from one host to multiple hosts or from multiple hosts, and the number of distributed on the Internet may reach hundreds of thousands of, which requires higher bandwidth and is far beyond the ability to unicast. An important technology that maximizes the use of existing bandwidth is IP multicast.


1. The concept of IP multicast technology

IP Multicast technology is a kind of TCP/IP network technology that allows one or more hosts (multicast sources) to send a single packet to multiple hosts (once, at the same time), which is a bit of communication to multiple points. In the application of network Multimedia broadcasting, when the signal of a node needs to be transmitted to multiple nodes, whether using the repetitive point-to-point communication mode or using the broadcast method, the network bandwidth will be seriously wasted, only the multicast is the best choice. Multicast enables one or more multicast sources to packages data only to specific multicast groups, and only hosts that join the multicast group can receive packets.

2. IP Multicast Address

IP multicast communication relies on IP multicast address, in IPV4 it is a class D IP address, ranging from 224.0.0.0 to 239.255 255.255, and is divided into local link multicast address, reserved multicast address and management rights multicast address three categories. where the local link multicast address range is 224.0.0.0~224.0.0.255, which is reserved for routing protocols and other purposes, routers do not forward IP packets belonging to this range; the reserved multicast address is 224.0.1.0~ 238.255.255.255 can be used for global purposes (such as the Internet) or network protocols; Administrative rights multicast addresses are 239.0.0.0~239.255.255.255 for internal use, similar to private IP addresses, not for the internet, can limit the multicast range.

3. Multicast group

All hosts that receive a multicast packet using the same IP multicast address form a host group, also known as a multicast unit. The members of a multicast group are changed at any time, a host can join or leave the multicast group at any time, the number of members of the multicast group and the geographical location are not restricted, and a host can belong to several multicast groups. In addition, a host that is not part of a multicast group can send packets to that multicast group.

This paper uses an instance of MulticastSocket class to write multicast applications, MulticastSocket classes provide connections and leave multicast operations.

Multisender Class List

Package recmail.multiservice;

Import java.net.*;
Import java.io.IOException;

/**
* This class encapsulates the MulticastSocket class, completes the creation and initialization of the MulticastSocket class instance,
* and provides an interface for sending data.
*/

public class Multisender {
public static final int multisender_port=4099;
Private MulticastSocket Road;
Private InetAddress IA;

Public Multisender () {
try {

Multicast address
ia = Inetaddress.getbyname ("239.66.69.18");
Road = new MulticastSocket (multisender_port);
Road.joingroup (IA);
}
catch (Unknownhostexception ex) {
}
catch (IOException Ex1) {
}
}
Public inetaddress getinetaddress () {
return IA;
}
Public MulticastSocket Getroad () {
Return road;
}
public void Send (byte[] b) {
Datagrampacket DP = new Datagrampacket (b, 0, B.length,
IA, Multisender.multisender_port);
try {
Road.send (DP);
}
catch (IOException ex) {
Ex.printstacktrace ();
}
}
}

Imageserver class, use the above class to send file data.

Package recmail.multiservice;
Import java.io.*;
Import Javax.swing.Timer;
Import java.awt.event.*;
Import java.awt.image.*;
Import java.util.*;
Import Java.io.FileFilter;
Import Java.io.FilenameFilter;

/**
* This class uses the Multisender class to send file data to a multicast group to send data.
*/

public class Imageserver
Extends Thread implements ActionListener {
Timer timer;
BufferedImage image;
ArrayList streamfragments;
int counter = 0;
Byte[] Imagebyte;
ArrayList Listener;
Multisender Sender;

Public Imageserver (ArrayList f) {
Timer = new timer (this);
Timer.addactionlistener (this);
Listener = new ArrayList ();
Streamfragments = f;
Sender = new Multisender ();
Timer.start ();
}

public void Adddataswaplistener (Dataswaplistener DSL) {
Listener.add (DSL);
}

public void Removedataswaplistener (Dataswaplistener DSL) {
Listener.remove (DSL);
}

private void processevent () {
for (int i = 0; i < this.listener.size (); i++) {
Dataswapevent DSE = new Dataswapevent ();
((Dataswaplistener) this.listener.get (i)). Ondatasendfinished (this, DSE);
}
}

public void actionperformed (ActionEvent e) {
Datapacket DP = new Datapacket (Streamfragments.get (counter). ToString ());
DataEntry de;
try {
ArrayList al = Dp.getdatapackets ();
Thread.Sleep (1000);
System.out.println (Streamfragments.get (counter). ToString ());
for (int i = 0; i < al.size (); i++) {
Imagebyte = ((DataEntry) al.get (i)). GetByte (); (byte[]) al.get (i);
Sender.send (Imagebyte);
}
This.processevent ();
}
catch (Exception ex) {
System.out.println (ex);
}
counter++;
if (Counter >= streamfragments.size ())
Counter = 0;
}

public void Run () {
while (true) {
try {
This.sleep (20);
}
catch (Interruptedexception ex) {
}
}
}

public static void Main (string[] args) {
String file[];
ArrayList al = new ArrayList ();
String Path = "e:\\mzip\\";
File F = new file (path);
File = F.list ();
for (int i = 0; i < file.length; i++) {
if (File[i].endswith ("jpg") | | file[i].endswith ("BMP")
Al.add (path + file[i]);
}
Imageserver is = new Imageserver (AL);
Is.start ();
}
}

Package recmail.multiservice;

Import java.net.*;
Import java.io.*;
Import java.awt.image.*;
/**
* This class encapsulates the MulticastSocket class, completes the creation and initialization of the MulticastSocket class instance,
* and provides a thread that receives data, generates events after the judgment is received, and updates the UI display.
* This class is used by Testframe.
*/
public class Imageshow
Extends Dataswaplisteneradapter
Implements Runnable {
Private InetAddress IA;
private int port = 4099;
Private MulticastSocket Road;
Dataswapevent dsevent;
Java.awt.image.BufferedImage bi;

Public Imageshow () {
Dsevent = new Dataswapevent (this);
try {
ia = Inetaddress.getbyname ("239.66.69.18");
Road = new MulticastSocket (port);
Road.joingroup (IA);
}
catch (IOException ex) {
}
}

public void Run () {
byte[] buffer = new Byte[datapacket.dataswapsize];
Datagrampacket packet = new Datagrampacket (buffer, buffer.length);
Datapacket DP = new Datapacket ();
while (true) {
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);
}
}
}
}

Receive End Interface class:

Package recmail.multiservice;

Import javax.swing.*;
Import java.awt.*;
Import java.awt.image.*;

/**
* This class uses imageshow to update the image displayed.
*/

public class Testframe
Extends JApplet
Implements Dataswaplistener {
private JPanel root;
JLabel label;
Jimagepanel IP;
Java.awt.Image bi;

Public Testframe () {
Initmain ();
}

public void init () {
Initmain ();
This.setcontentpane (root);
Imageshow is = new Imageshow ();
Is.adddataswaplistener (this);
Thread thread = new Thread (IS, "test");
Thread.Start ();
}

public static void Main (string[] args) {
Testframe test = new Testframe ();
Test.go (New JFrame ());
Imageshow is = new Imageshow ();
Is.adddataswaplistener (test);
Thread thread = new Thread (IS, "test");
Thread.Start ();
}

public void Go (JFrame frame) {
Frame.setcontentpane (root);
Frame.setsize (300, 200);
Frame.setdefaultcloseoperation (Jframe.exit_on_close);
Frame.validate ();
Frame.setvisible (TRUE);
}

public void Initmain () {
root = new JPanel ();
label = new JLabel ();
ip = new Jimagepanel ();
Root.setlayout (New BorderLayout (5, 5));
Root.add (IP, borderlayout.center);
}

public void Setrefreshimage (Java.awt.image.BufferedImage img) {
This.bi = img;
Ip.setimage (BI);
}

public void Paint (Graphics g) {
Super.paint (g);
}

public void Paintcomponents (Graphics g) {
Super.paintcomponents (g);
Graphics G1 = Root.getgraphics ();
G1.drawimage (BI, 0, 0, this);
}

public void ondatasendfinished (Object s, dataswapevent e) {

}

public void ondatarecvfinished (Object s, dataswapevent e) {
This.bi = E.getimage ();
Ip.setimage (BI);
System.out.println ("recv finished!");
}
}

Here, this multicast program is written, through this program can be seen in Java multicast programming has two characteristics, one is to use Java MulticastSocket class, and the second is to use the multicast address configuration MulticastSocket instance.

The full content of the datagram programming is over, and if it is to be improved, it can be done in two ways, one to improve the reliability of the transmission, one is to adopt the asynchronous aspect of data sending and receiving, because in j2sdk1.4 the MulticastSocket class adds method Getchannel ().




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.