Java Peer-to-peer Computing Practice: Discovery based on IP multicast

Source: Internet
Author: User
Tags abstract implement interface net socket thread throwable port number
To accomplish useful work, peers in peer-to-peer applications must be able to discover each other and interact with each other. This article provides an implementation of a discovery based on IP multicast.

Before a software entity can participate in a direct peer-to-peer interaction with a Peer-to-peer application feature, the entity must discover the appropriate peers to interact with. All available Peer-to-peer architectures provide a solution for discovery problems. In this article I will describe the implementation of one of these mechanisms. Let us begin today's discussion by looking back. Revisit Discovery Peer-to-peer discovery allows peers in peer-to-peer applications to locate each other so that they can interact with each other. There are several ways to implement Peer-to-peer discovery services. The simplest mechanism is an explicit point-to-point configuration. This mechanism works by requiring each peer to know all other peers that it may interact with and to connect to them. The primary advantage of point-to-point configuration is simplicity. Its main disadvantage is the lack of flexibility and the lack of capacity to scale large networks that extend to peers.

Another common model found is the use of a central directory as an intermediary. The model is popular among many traditional, non peer-to-peer distributed types of applications, and its advantages are well understood. Peers register their presence with a central directory and use a central directory to locate other peers. The main advantage of this model is the ability to manage and scale easily. However, its centralized design leads to a single point of failure, so it lacks the ability to withstand the damage caused by natural forces or the increase in the number of Internet surfers.

Many popular peer-to-peer applications use a network model rather than a central directory, in which a single peer knows only the identity of peers on the local domain network. Each peer is a directory of those peers that are connected to it. Peers collaborate by propagating directory queries to neighboring peers and returning related responses. The main advantage of this model is the lack of centralization. Its main disadvantage is that the propagation of queries consumes a lot of network and processing power.

There are numerous variants of the above three mechanisms. Without discussing these variants, let's go ahead and study another discovery mechanism.

IP Multicast Discovery

The multicast model is similar to the network model in terms of maintaining your own directory for each peer. However, peers do not implement large-scale network queries through collaboration. In addition, peers use the features provided by the network itself (IP multicast) to locate and identify other peers.

IP multicast is connectionless and unreliable (unlike TCP/IP is connection-oriented and reliable). Although it uses IP datagrams, unlike unicast IP datagrams, which are sent from one host to another, multicast IP datagrams can be sent to multiple hosts at the same time.

Peers periodically use IP multicasting to announce their presence. Declares that they contain their hostname and a port for normal communication. The peer that is interested in this message detects the message, extracts the host name and port number, and uses the message to establish a communication channel.

The review is enough. Let's get started on the code.



Simple client and server

We'll start with a simple example that shows how two processes use IP multicast for communication. To simplify the demo, I'll introduce the example from both the client and server processes. Peer-to-peer applications typically implement both processes, and it is not easy to divide them into clients or servers.

In this case, the server process loops and waits for the datagram to arrive. Each packet is received, and the server prints a short diagnostic message to the console. Client roles are much simpler? It multicast individual datagram packets and exits.

Listings 1 and 2 illustrate how the two parts are grouped together. The comments in the code explain what is going on.

Listing 1. Simple server


Public
Class Server
{
Public
Static
void
Main (String [] arstring)
{
Try
{
Create a multicast datagram socket for receiving IP
Multicast packets. Join the multicast group at
230.0.0.1, Port 7777.
MulticastSocket multicastsocket = new MulticastSocket (7777);
InetAddress inetaddress = Inetaddress.getbyname ("230.0.0.1");
Multicastsocket.joingroup (inetaddress);
Loop forever and receive messages from clients. Print
The received messages.
while (true)
{
byte [] arb = new byte [100];
Datagrampacket datagrampacket = new Datagrampacket (ARB, arb.length);
Multicastsocket.receive (Datagrampacket);
System.out.println (New String (ARB));
}
}
catch (Exception Exception)
{
Exception.printstacktrace ();
}
}
}

Listing 2. Simple Client


Public
Class Client
{
Public
Static
void
Main (String [] arstring)
{
Try
{
Create a datagram package and send it to the multicast
Group at 230.0.0.1, Port 7777.
byte [] arb = new Byte [] {' H ', ' e ', ' l ', ' l ', ' o '};
InetAddress inetaddress = Inetaddress.getbyname ("230.0.0.1");
Datagrampacket Datagrampacket =
New Datagrampacket (ARB, Arb.length, inetaddress, 7777);
MulticastSocket multicastsocket = new MulticastSocket ();
Multicastsocket.send (Datagrampacket);
}
catch (Exception Exception)
{
Exception.printstacktrace ();
}
}
}

The two classes in the java.net package make it run. The Java.net.DatagramPacket class holds the data contained in the IP datagram package. The Java.net.MulticastSocket class creates a multicast socket that adjusts to a specific multicast group.

Discovery Component

Although the above example is a good demonstration of IP multicasting, it does not explain what is needed to implement Peer-to-peer discovery based on IP multicast. To make it useful, we need a software component that is not limited to sending and receiving packages. Ideally, the component will understand the source peer of the packet it receives and discard some information appropriately about peers that it believes has disappeared, died, or otherwise departed.

In this new design, a peer is a member of a multicast group. Keep in mind that messages sent to a multicast group are transparently routed to all members of that group.

The design includes two core classes and three interfaces (I use the term "interface" seems less rigorous?) is technically an interface and two abstract classes). An instance of the Member class is one of the members of a multicast group. This class manages all communication details. An instance of the Membermanager class is responsible for understanding other members participating in the multicast group.

Peers declare their presence to peers that belong to a multicast group by sending a message to the multicast group. Each message contains information about the peer that sent the message? Typically, the host name and the port used for normal (unrelated to discovery) traffic. The member class and the Membermanager class know little about the content of these messages. Access to this information belongs to an application that uses these two classes.

There are three interfaces that span the boundaries between the messaging/Discovery layer and the application layer that uses it. They are Reference abstract classes, message interfaces, and Messagefactory abstract classes. The application must provide implementations of these three interfaces.

The Reference abstract class defines a reference to a member of a multicast group. The Membermanager class manages a reference set. The application will implement a specific version of this class that will contain any referential logic required by the application. The class defines two methods, the name is Equalsinternal () and hashcodeinternal (), and the Equals () and Hashcode () methods are redefined to invoke these methods. Does it force the implementation to provide implementations for these two key features by doing so? Membermanager depend on them.

The message interface defines an application view of messaging data exchanged over network code. Does the application view this message as a high-level concept relative to the scope of application execution? A concept similar to hostname and port. The network code wants to send a packet consisting of bytes. The implementation of the message interface defines how these advanced information is converted to bytes. A reference is a key part of the information, and all messages must be contained, so the interface requires the implementation to provide methods for reading and writing reference.

The last part of the problem is the Messagefactory abstract class. This class defines the mechanism for generating a new instance of message. The network code deep inside the member class uses a factory to create a message instance of the data extracted from the multicast datagram. Each messagefactory instance has a randomly generated identity that uses this identity to filter out messages to be sent from the received message.

In summary, these five classes and interfaces (member, Membermanager, Reference, message, and messagefactory) Form a simple framework for peer discovery. Of course, there is room to improve. You can easily add an event-based mechanism to notify interested listeners of the presence or disappearance of a member. A flexible mechanism for filtering incoming messages is useful, but it is difficult to implement. I leave these suggestions for the reader's homework.


Member class

The complete source code for the framework described above is too long to be shown in detail, so let's just look at part of the code for the member class, which contains most of the action. More precisely, the operation takes place within two internal classes: the Memberclient class and the Memberserver class.

Please consider the first example again. It consists of a client that sends an IP multicast datagram and a server that receives datagrams. In this example (listings 3 and 4), two separate applications perform these two functions. Peers in Peer-to-peer applications behave in a way that is both client and server, so our Peer-to-peer applications should contain both.

Listing 3. Memberclient class


Private
Class Memberclient
Extends Thread
{
Public
void
Run ()
{
Try
{
while (true)
{
Try
{
Message message = M_messagefactory.createsendmessage ();
Reference Reference = Message.createreference ();
Message.writereference (reference);
Message.sync ();
byte [] arb = Message.getbytearray ();
Datagrampacket datagrampacket = new Datagrampacket (ARB, arb.length);
Datagrampacket.setaddress (m_inetaddress);
Datagrampacket.setport (M_nport);
MulticastSocket multicastsocket = new MulticastSocket ();
Multicastsocket.send (Datagrampacket);
}
catch (IOException IOException)
{
Ioexception.printstacktrace ();
}
Try
{
Synchronized (This)
{
Wait (m_nperiod);
}
}
catch (Interruptedexception interruptedexception)
{
Break
}
}
}
catch (Throwable throwable)
{
Throwable.printstacktrace ();
}
}
}

Listing 3 contains the source code for the Memberclient class. Like the client in Listing 1, the client creates a MulticastSocket instance and uses it to send a datagrampacket instance. The Datagrampacket instance contains a reference to the sender peer, which is encoded as a byte array. As long as the peer is active and running, the client broadcasts the message at regular intervals.

Listing 4. Memberserver class


Private
Class Memberserver
Extends Thread
{
Public
void
Run ()
{
Try
{
MulticastSocket multicastsocket = new MulticastSocket (m_nport);
Multicastsocket.joingroup (m_inetaddress);
while (true)
{
Message message = M_messagefactory.createreceivemessage ();
byte [] arb = Message.getbytearray ();
Datagrampacket datagrampacket = new Datagrampacket (ARB, arb.length);
Multicastsocket.receive (Datagrampacket);
Message.sync ();
if (m_messagefactory.ismine (message) = = False)
{
Reference Reference = Message.createreference ();
Message.readreference (reference);
M_membermanager.addreference (reference);
}
}
}
catch (Throwable throwable)
{
Throwable.printstacktrace ();
}
}
}

The Memberserver class is similar in many respects to the server in Listing 2. In addition to creating the necessary code, using it to collect the appropriate datagram from the established communication (wire), the server decodes the encoded reference, creates the message, and passes the message to the Membermanager instance for safekeeping. Well done.

The remainder of the class consists of a read and write method for various attributes and a start () and Stop () method for controlling the life cycle of the class.

Peer-to-peer applications

The peer Discovery Framework is complete, and all that remains is to integrate it into the existing Peer-to-peer application. There are relatively few changes to the original Peer-to-peer application.

First, in its predecessor, Peer-to-peer applications expect to list all known peers in their attribute files. Although this is good for demonstration purposes (recall the point-to-point configuration discussed above) and works well for up to approximately four peers, it is ultimately too restrictive. Therefore, the code to read and manage peers in an attribute file is removed and replaced with code that uses the discovery mechanism above.

Second, because the peers are enumerated in the attribute file, it looks as if they are persistent. Existing applications are sometimes lucky to succeed if they are assumed to not disappear. But in a peer-to-peer real world, things change more easily. New applications are redesigned to better recover when peers disappear.

Updated source code can be obtained in resources


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.