+ All Categories
Home > Documents > Lezione 9 - UNISAcordasco/teaching/ASDAD0809/lezione9.pdf · 15/12/2008 3 Le vostre domande yOrali?...

Lezione 9 - UNISAcordasco/teaching/ASDAD0809/lezione9.pdf · 15/12/2008 3 Le vostre domande yOrali?...

Date post: 13-Jul-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
9
15/12/2008 1 Sistemi Peer to Peer Gennaro Cordasco Dipartimento di Informatica e Applicazioni Università degli Studi di Salerno cordasco[@]dia.unisa.it cordasco+p2p[@]gmail.com http://www.dia.unisa.it/~cordasco Laboratorio ISISLAB 2 (DIA Piano 2) 15/12/2008 1 Materiale didattico i) PeertoPeer Systems and Applications Series: Lecture Notes in Computer Science , Vol. 3485 Sublibrary: Information Systems and Applications, incl. Internet/Web, and HCI www.peertopeer.info Steinmetz, Ralf; Wehrle, Klaus (Eds.) 2005, XVII, 629 p. With online files/update., Softcover ISBN: 9783540291923 ii) Research papers (http://www dia unisa it/~cordasco) 15/12/2008 2 ii) Research papers (http://www.dia.unisa.it/ cordasco ) iii) JXTA java Programmers guide (http://www.dia.unisa.it/~cordasco ) iv) JXTA Protocol Specifications (http://www.dia.unisa.it/~cordasco ) v) Le slide del corso (http://www.dia.unisa.it/~cordasco ) … che ovviamente non sono sufficienti per superare l’esame!!! y 13/10 DHT + Chord (1 a parte) y 20/10 Chord (2 a parte) + Consistent Hashing y 27/10 Altre DHT + LB y 03/11 JXTA y 10/11 JXTA y 17/11 Esercitazioni (parte teorica) y 1/12 Prova scritta y 15/12 JXTA y 22/12 …. Buon Natale … 15/12/2008 3 Le vostre domande y Orali? Tutti i venerdì dal 16 Gennaio a fine Febbraio (max 6 su prenotazione). Tutti possono partecipare (verdi, gialli e rossi) Per la registrazione prenotatevi sulla piattaforma. Nuova prova scritta a Febbraio (almeno 20 prenotati). Progetti JXTA (facoltativo) da richiedere almeno un mese prima della prova. 15/12/2008 4 Lezione 9 y Hello World y WorkingWithLocalConfig y Peer Discovery y Group Discovery y Publish Demo y Join Demo y Discovery y Pipe y Socket JXTA: Hello World JXTA: Hello World y Requirement Requirement Java SDK ( Java SDK (http://java.sun.com http://java.sun.com )[ )[jdk1.6] jdk1.6] JXTA ( JXTA (http://download.jxta.org/index.html) http://download.jxta.org/index.html) [JXTA 2 5] [JXTA 2 5] [JXTA 2.5] [JXTA 2.5] x jxse jxse-lib lib-2.5 2.5 x jxse jxse-tutorials tutorials-2.5 2.5 x jxse jxse-doc doc-2.5 2.5
Transcript
Page 1: Lezione 9 - UNISAcordasco/teaching/ASDAD0809/lezione9.pdf · 15/12/2008 3 Le vostre domande yOrali? Tutti i venerdì dal 16 Gennaioa fine Febbraio (max 6 su prenotazione). Tuttipossono

15/12/2008

1

Sistemi Peer to Peer

Gennaro CordascoDipartimento di Informatica e ApplicazioniUniversità degli Studi di Salernocordasco[@]dia.unisa.it cordasco+p2p[@]gmail.comhttp://www.dia.unisa.it/~cordascoLaboratorio ISISLAB2 (DIA Piano 2)

15/12/2008 1

Materiale didatticoi) Peer‐to‐Peer Systems and ApplicationsSeries: Lecture Notes in Computer Science , Vol. 3485 Sublibrary: Information Systems and Applications, incl. Internet/Web, and HCI www.peer‐to‐peer.infoSteinmetz, Ralf; Wehrle, Klaus (Eds.) 2005, XVII, 629 p. With online files/update., SoftcoverISBN: 978‐3‐540‐29192‐3

ii) Research papers (http://www dia unisa it/~cordasco)

15/12/2008 2

ii) Research papers (http://www.dia.unisa.it/ cordasco)

iii) JXTA java Programmers guide (http://www.dia.unisa.it/~cordasco)

iv) JXTA Protocol Specifications (http://www.dia.unisa.it/~cordasco)

v) Le slide del corso (http://www.dia.unisa.it/~cordasco) … che ovviamente non sono sufficienti per superare l’esame!!!

13/10 DHT + Chord (1a parte)20/10 Chord (2a parte) + Consistent Hashing27/10 Altre DHT + LB03/11 JXTA10/11 JXTA17/11 Esercitazioni (parte teorica)1/12 Prova scritta15/12 JXTA22/12 ….  Buon Natale … 

15/12/2008 3

Le vostre domande

Orali?◦ Tutti i venerdì dal 16 Gennaio a fine Febbraio(max 6 su prenotazione). Tutti possonopartecipare (verdi, gialli e  rossi)◦ Per la registrazione prenotatevi sullapiattaforma.◦ Nuova prova scritta a Febbraio (almeno 20 prenotati).◦ Progetti JXTA (facoltativo) da richiederealmeno un mese prima della prova.

15/12/2008 4

Lezione 9

Hello WorldWorkingWithLocalConfigPeer DiscoveryGroup Discoveryp yPublish DemoJoin DemoDiscoveryPipeSocket

JXTA: Hello WorldJXTA: Hello World

RequirementRequirement◦◦ Java SDK (Java SDK (http://java.sun.comhttp://java.sun.com)[)[jdk1.6]jdk1.6]◦◦ JXTA (JXTA (http://download.jxta.org/index.html) http://download.jxta.org/index.html)

[JXTA 2 5] [JXTA 2 5] [JXTA 2.5] [JXTA 2.5] jxsejxse--liblib--2.52.5jxsejxse--tutorialstutorials--2.52.5jxsejxse--docdoc--2.52.5

Page 2: Lezione 9 - UNISAcordasco/teaching/ASDAD0809/lezione9.pdf · 15/12/2008 3 Le vostre domande yOrali? Tutti i venerdì dal 16 Gennaioa fine Febbraio (max 6 su prenotazione). Tuttipossono

15/12/2008

2

JXTA: Hello WorldJXTA: Hello World

Compilare usando JXTA◦ javac ‐classpath .\lib\jxta.jar SimpleJxtaApp.java

Lanciare un applicazione◦ java ‐classpath .\lib\jxta.jar .\lib\bcprov‐jdk14.jar;. SimpleJxtaAppj p \ \j j \ \ p j j ; p pp

JXTA: Hello WorldJXTA: Hello World

DemoDemoJXTA: JXTA: WorkingWithLocalConfigurationWorkingWithLocalConfigurationimport net.jxta.exception.PeerGroupException;import net.jxta.peergroup.PeerGroup;import net.jxta.platform.NetworkConfigurator;import net.jxta.platform.NetworkManager;import java.text.MessageFormat;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader;import javax.security.cert.CertificateException;import javax.swing.JOptionPane;

public class WorkingWithLocalConfiguration {public class WorkingWithLocalConfiguration {public static final String Local_Peer_Name = "My Local Peer";public static final String Local_Network_Manager_Name = "My Local Network Manager";NetworkManager TheNetworkManager;NetworkConfigurator TheConfig;PeerGroup TheNetPeerGroup;

public WorkingWithLocalConfiguration() {try {

System.out.println("Creating the Network Manager");TheNetworkManager = new NetworkManager( NetworkManager.ConfigMode.EDGE,

Local_Network_Manager_Name);System.out.println("Network Manager created");

} catch (IOException ex) {ex.printStackTrace();System.exit(-1);

}

JXTA: JXTA: WorkingWithLocalConfigurationWorkingWithLocalConfiguration// Persisting it to make sure the Peer ID is not re-created each time the Network Manager is instantiatedTheNetworkManager.setConfigPersistent(true); System.out.println("PeerID: " + TheNetworkManager.getPeerID().toString());TheNetworkManager.setUseDefaultSeeds(true);System.out.println("Retrieving the Network Configurator");try {

TheConfig = TheNetworkManager.getConfigurator();} catch (IOException e) { e.printStackTrace(); }System.out.println("Network Configurator retrieved");if (TheConfig.exists()) {

System.out.println("Local configuration found");File LocalConfig = new File(TheConfig.getHome(), "PlatformConfig");try {try {

System.out.println("Loading found configuration");TheConfig.load(LocalConfig.toURI());System.out.println("Configuration loaded");

} catch (Exception ex) { System.exit(-1); } } else {

System.out.println("No local configuration found");TheConfig.setName(Local_Peer_Name);TheConfig.setPrincipal(GetPrincipal());TheConfig.setPassword(GetPassword());System.out.println("Principal: " + TheConfig.getPrincipal());System.out.println("Password : " + TheConfig.getPassword());try {

System.out.println("Saving new configuration");TheConfig.save();} catch (IOException ex) { System.exit(-1); }

}

JXTA: JXTA: WorkingWithLocalConfigurationWorkingWithLocalConfigurationpublic void SeekRendezVousConnection() {

try {System.out.println("Starting JXTA");TheNetPeerGroup = TheNetworkManager.startNetwork();System.out.println("JXTA Started");System.out.println("Peer name : “ + TheNetPeerGroup.getPeerName());System.out.println("Peer Group name: “ + TheNetPeerGroup.getPeerGroupName());System.out.println("Peer Group ID : “ + TheNetPeerGroup.getPeerID().toString());

} catch (PeerGroupException ex) {ex.printStackTrace();System.exit(-1);

} catch (IOException ex) {ex printStackTrace();ex.printStackTrace();System.exit(-1);

}System.out.println("Waiting for a rendezvous connection for 25 seconds (maximum)");boolean connected = TheNetworkManager.waitForRendezvousConnection(25000);System.out.println(MessageFormat.format("Connected :{0}", connected));

System.out.println("Stopping JXTA");TheNetworkManager.stopNetwork();

}

public static void main(String[] args) {WorkingWithLocalConfiguration MyLogin = new WorkingWithLocalConfiguration();MyLogin.SeekRendezVousConnection();

}}

Page 3: Lezione 9 - UNISAcordasco/teaching/ASDAD0809/lezione9.pdf · 15/12/2008 3 Le vostre domande yOrali? Tutti i venerdì dal 16 Gennaioa fine Febbraio (max 6 su prenotazione). Tuttipossono

15/12/2008

3

DemoDemo PeerPeer DiscoveryDiscoverypublic class PeerDiscovery implements DiscoveryListener {private transient NetworkManager manager;private transient DiscoveryService discovery;// Constructor for the PeerDiscoverypublic PeerDiscovery() {try {manager = new

NetworkManager(NetworkManager.ConfigMode.EDGE, "PeerDiscovery"

package peerdiscovery;import net.jxta.discovery.DiscoveryEvent;import net.jxta.discovery.DiscoveryListener;import net.jxta.discovery.DiscoveryService;import net.jxta.peergroup.PeerGroup;import net.jxta.platform.NetworkManager;import net.jxta.protocol.DiscoveryResponseMsg;import net.jxta.protocol.PeerAdvertisement;import java.io.File;import java.util.Enumeration;

PeerDiscovery ,new File(new File(".cache"), 

"PeerDiscovery").toURI());manager.startNetwork();

} catch (Exception e) {e.printStackTrace();System.exit(‐1);

}PeerGroup netPeerGroup = manager.getNetPeerGroup();// get the discovery servicediscovery = netPeerGroup.getDiscoveryService();

}

15/12/2008 14

PeerPeer DiscoveryDiscoverypublic static void main(String args[]) {

PeerDiscovery myapp = new PeerDiscovery();myapp.start();

}

public void start() {long waittime = 30 * 1000L;try {discovery.addDiscoveryListener(this);while (true) {discovery.getRemoteAdvertisements(null, DiscoveryService.PEER, null, null, 5);try {

System.out.println("Sleeping for :" + waittime);y p ( p g f );Thread.sleep(waittime);

} catch (Exception e) {// ignored}

}} catch (Exception e) {e.printStackTrace();

}}

15/12/2008 15

PeerPeer DiscoveryDiscovery

public void discoveryEvent(DiscoveryEvent ev) {

DiscoveryResponseMsg res = ev.getResponse();

// let's get the responding peer's advertisement

System.out.println(" [  Got a Discovery Response [" + res.getResponseCount() + " elements]  from peer : " + ev.getSource() + "  ]");

PeerAdvertisement adv;

Enumeration en = res.getAdvertisements();

if (en != null) {

while (en hasMoreElements()) {while (en.hasMoreElements()) {

adv = (PeerAdvertisement) en.nextElement();

System.out.println("Peer Name = "+ adv.getName());

}

}

}

//Stops the platform

public void stop() {

// Stop JXTA

manager.stopNetwork();

}

15/12/2008 16

DemoDemoGroup Group DiscoveryDiscoveryimport net.jxta.discovery.DiscoveryEvent;import net.jxta.discovery.DiscoveryListener;import net.jxta.discovery.DiscoveryService;import net.jxta.peergroup.PeerGroup;import net.jxta.platform.NetworkManager;import net.jxta.protocol.DiscoveryResponseMsg;import net.jxta.protocol.PeerGroupAdvertisement;import java.io.File;import java.util.Enumeration;

public class GroupDiscovery implements DiscoveryListener {private transient NetworkManager manager;private transient DiscoveryService discovery;public GroupDiscovery() {public GroupDiscovery() {try {manager = new NetworkManager(NetworkManager.ConfigMode.EDGE, "GroupDiscovery",

new File(new File(".cache"), "GroupDiscovery").toURI());manager.startNetwork();

} catch (Exception e) {e.printStackTrace();System.exit(‐1);

}PeerGroup netPeerGroup = manager.getNetPeerGroup();// get the discovery servicediscovery = netPeerGroup.getDiscoveryService();

}

15/12/2008 18

Page 4: Lezione 9 - UNISAcordasco/teaching/ASDAD0809/lezione9.pdf · 15/12/2008 3 Le vostre domande yOrali? Tutti i venerdì dal 16 Gennaioa fine Febbraio (max 6 su prenotazione). Tuttipossono

15/12/2008

4

Group Group DiscoveryDiscoverypublic static void main(String args[]) {

GroupDiscovery myapp = new GroupDiscovery();myapp.start();

}

public void start() {    long waittime = 30 * 1000L;try {discovery.addDiscoveryListener(this);while (true) {discovery.getRemoteAdvertisements(null, DiscoveryService.GROUP, null, null, 5);try {y {

System.out.println("Sleeping for :" + waittime);Thread.sleep(waittime);

} catch (Exception e) {// ignored}

}} catch (Exception e) {e.printStackTrace();

}}

15/12/2008 19

Group Group DiscoveryDiscovery

public void discoveryEvent(DiscoveryEvent ev) {DiscoveryResponseMsg res = ev.getResponse();// let's get the responding peer's advertisementSystem.out.println(" [  Got a Discovery Response [" + res.getResponseCount() + " elements]  from peer : " + ev.getSource() + "  ]");PeerGroupAdvertisement adv;Enumeration en = res.getAdvertisements();if (en != null) {while (en.hasMoreElements()) {adv = (PeerGroupAdvertisement) en.nextElement();S t t i tl ("P N "+ d tN ())System.out.println("Peer Name = "+ adv.getName());

}}

}

public void stop() {// Stop JXTAmanager.stopNetwork();

}}

15/12/2008 20

DemoDemoPublishPublish DemoDemoimport net.jxta.discovery.DiscoveryService;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroupID;import net.jxta.platform.NetworkManager;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader;import net.jxta.protocol.ModuleImplAdvertisement;import net.jxta.protocol.PeerGroupAdvertisement;import java.util.Enumeration;

public class PublishDemo {private transient NetworkManager manager;private transient DiscoveryService discoSvc;private PeerGroup myGroup;

public PublishDemo() {try {manager = new NetworkManager(NetworkManager.ConfigMode.EDGE, "PublishDemo",

new File(new File(".cache"), "PublishDemo").toURI());manager.startNetwork();

} catch (Exception e) {e.printStackTrace();System.exit(‐1);

}myGroup = manager.getNetPeerGroup();// get the discovery servicediscoSvc = myGroup.getDiscoveryService();

} 15/12/2008 22

PublishPublish DemoDemopublic static void main(String args[]) {

PublishDemomyapp = new PublishDemo();myapp.groupsInLocalCache();myapp.createGroup();myapp.groupsInLocalCache();    System.exit(0);      }

private void groupsInLocalCache() {System.out.println("‐‐‐ local cache (Peer Groups)  ‐‐‐");try {

d d llPeerGroupAdvertisement adv = null;Enumeration en = discoSvc.getLocalAdvertisements(DiscoveryService.GROUP, null, null);if (en != null) {while (en.hasMoreElements()) {adv = (PeerGroupAdvertisement) en.nextElement();System.out.println( adv.getName() + ", group ID = " +

adv.getPeerGroupID().toString());}

}} catch (Exception e) {}System.out.println("‐‐‐ end local cache ‐‐‐");

}

15/12/2008 23

PublishPublish DemoDemoprivate void createGroup() {

PeerGroupAdvertisement adv;System.out.println("Creating a new group advertisement");try {               // create a new all purpose peergroup.ModuleImplAdvertisement implAdv = myGroup.getAllPurposePeerGroupImplAdvertisement(PeerGroup pg = myGroup.newGroup(null,                // Assign new group ID

implAdv,              // The implem. adv"Publish Test" +  " ",            // The name"testing group adv"); // Helpful descr.

adv = pg.getPeerGroupAdvertisement();PeerGroupID GID = adv.getPeerGroupID();System.out.println("  Group = " +adv.getName() +  "\n Group ID = " + GID.toString());

} catch (Exception eee) {System.out.println("Group creation failed with " + eee.toString());return;

}try {// publish this advertisementdiscoSvc.remotePublish(adv);System.out.println("Group published successfully.");

} catch (Exception e) {System.out.println("Error publishing group advertisement");e.printStackTrace();return;

}}

15/12/2008 24

Page 5: Lezione 9 - UNISAcordasco/teaching/ASDAD0809/lezione9.pdf · 15/12/2008 3 Le vostre domande yOrali? Tutti i venerdì dal 16 Gennaioa fine Febbraio (max 6 su prenotazione). Tuttipossono

15/12/2008

5

DemoDemoJoin DemoJoin Demoimport java.io.StringWriter;import net.jxta.credential.AuthenticationCredential;import net.jxta.credential.Credential;import net.jxta.document.StructuredDocument;import net.jxta.document.StructuredTextDocument;import net.jxta.document.MimeMediaType;import net.jxta.membership.Authenticator;import net.jxta.membership.MembershipService;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroupID;import net.jxta.protocol.PeerGroupAdvertisement;import net.jxta.protocol.ModuleImplAdvertisement;import net.jxta.discovery.DiscoveryService;import net.jxta.platform.NetworkManager;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader;

public class JoinDemo {private transient NetworkManager manager;private transient DiscoveryService discoSvc;private PeerGroup myGroup=null;

public JoinDemo() {try {manager = new NetworkManager(NetworkManager.ConfigMode.EDGE, "JoinDemo",

new File(new File(".cache"), "JoinDemo").toURI());manager.startNetwork();

} catch (Exception e) { System.exit(‐1);  }myGroup = manager.getNetPeerGroup();// get the discovery servicediscoSvc = myGroup.getDiscoveryService();

} 15/12/2008 26

Join DemoJoin Demopublic static void main(String args[]) {

JoinDemo myapp = new JoinDemo();PeerGroup newGroup = myapp.createGroup();if (newGroup != null) myapp.joinGroup(newGroup); System.out.println("Good Bye ....");manager.stopNetwork();System.exit(0);

} // create and publish a new peer groupprivate PeerGroup createGroup() {

PeerGroupAdvertisement adv;PeerGroup pg;System.out.println("Creating a new group advertisement");try { // create a new all purpose peergroup.

15/12/2008 27

ModuleImplAdvertisement implAdv =myGroup.getAllPurposePeerGroupImplAdvertisement();pg = myGroup.newGroup(null, // Assign new group ID

implAdv, // The implem. adv"Join Test" + " ", // The name"testing group adv"); // Helpful descr.

adv = pg.getPeerGroupAdvertisement();PeerGroupID GID = adv.getPeerGroupID();System.out.println(" Group = " +adv.getName() + "\n Group ID = " + GID.toString());

} catch (Exception eee) { return null; }try { // publish this advertisement

discoSvc.remotePublish(adv);System.out.println("Group published successfully.");

} catch (Exception e) { return null; }return pg;

}

Join DemoJoin Demoprivate void joinGroup(PeerGroup grp) {

System.out.println("Joining peer group...");StructuredDocument creds = null;try { // Generate the credentials for the Peer GroupAuthenticationCredential authCred = new AuthenticationCredential( grp, null, creds );// Get the MembershipService from the peer groupMembershipService membership = grp.getMembershipService();// Get the Authenticator from the Authentication credsAuthenticator auth = membership.apply(authCred );// Check if everything is okay to join the groupif (auth.isReadyForJoin()){

Credential myCred = membership.join(auth);System.out.println("Successfully joined group " + grp.getPeerGroupName());// display the credential as a plain text document.

15/12/2008 28

p y pSystem.out.println("\nCredential: ");StructuredTextDocument doc = (StructuredTextDocument)

myCred.getDocument(new MimeMediaType("text/plain"));StringWriter out = new StringWriter();doc.sendToWriter(out);System.out.println(out.toString());out.close();

}else

System.out.println("Failure: unable to join group");}catch (Exception e){

System.out.println("Failure in authentication.");e.printStackTrace();

}}

DemoDemoDiscoveryDiscovery (Server)(Server)import net.jxta.discovery.DiscoveryService;import net.jxta.document.AdvertisementFactory;import net.jxta.id.IDFactory;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroupID;import net.jxta.pipe.PipeService;import net.jxta.platform.NetworkManager;import net.jxta.protocol.PipeAdvertisement;import java.io.File;

public class DiscoveryServer {private transient NetworkManager manager;private transient DiscoveryService discovery;

public DiscoveryServer() {

15/12/2008 30

p y () {try {

manager = new NetworkManager(NetworkManager.ConfigMode.EDGE, "DiscoveryServer",new File(new File(".cache"), "DiscoveryServer").toURI());

manager.startNetwork();} catch (Exception e) {

System.exit(-1);}PeerGroup netPeerGroup = manager.getNetPeerGroup();// get the discovery servicediscovery = netPeerGroup.getDiscoveryService();

}

Page 6: Lezione 9 - UNISAcordasco/teaching/ASDAD0809/lezione9.pdf · 15/12/2008 3 Le vostre domande yOrali? Tutti i venerdì dal 16 Gennaioa fine Febbraio (max 6 su prenotazione). Tuttipossono

15/12/2008

6

DiscoveryDiscovery (Server)(Server)public static void main(String args[]) {

DiscoveryServer disocveryServer = new DiscoveryServer();disocveryServer.start();

}

// create a new pipe adv, publish it for 2 minut network time,public void start() {

long lifetime = 60 * 2 * 1000L;long expiration = 60 * 2 * 1000L;long waittime = 60 * 3 * 1000L;try {

while (true) {PipeAdvertisement pipeAdv = getPipeAdvertisement();// publish the advertisement with a lifetime of 2 mintutes

15/12/2008 31

pSystem.out.println(

"Publishing the following advertisement with lifetime :" + lifetime);System.out.println(pipeAdv.toString());discovery.publish(pipeAdv, lifetime, expiration);discovery.remotePublish(pipeAdv, expiration);try {

System.out.println("Sleeping for :" + waittime);Thread.sleep(waittime);

} catch (Exception e) {// ignored}

}} catch (Exception e) {

e.printStackTrace();}

}

DiscoveryDiscovery (Server)(Server)/**

* Creates a pipe advertisement*/public static PipeAdvertisement getPipeAdvertisement() {

PipeAdvertisement advertisement = (PipeAdvertisement)AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());advertisement.setPipeID(IDFactory.newPipeID(PeerGroupID.defaultNetPeerGroupID));advertisement.setType(PipeService.UnicastType);advertisement.setName("Discovery tutorial");return advertisement;

}

public void stop() {

15/12/2008 32

manager.stopNetwork();}

DiscoveryDiscovery (Client)(Client)import net.jxta.discovery.DiscoveryEvent;import net.jxta.discovery.DiscoveryListener;import net.jxta.discovery.DiscoveryService;import net.jxta.document.Advertisement;import net.jxta.peergroup.PeerGroup;import net.jxta.platform.NetworkManager;import net.jxta.protocol.DiscoveryResponseMsg;import java.io.File;import java.util.Enumeration;public class DiscoveryClient implements DiscoveryListener {private transient NetworkManager manager;

private transient DiscoveryService discovery;

15/12/2008 33

public DiscoveryClient() {try {

manager = new NetworkManager(NetworkManager.ConfigMode.EDGE, "DiscoveryClient",new File(new File(".cache"), "DiscoveryClient").toURI());

manager.startNetwork();} catch (Exception e) {

e.printStackTrace();System.exit(-1);

}// Get the NetPeerGroupPeerGroup netPeerGroup = manager.getNetPeerGroup();// get the discovery servicediscovery = netPeerGroup.getDiscoveryService();

}

DiscoveryDiscovery (Client)(Client)public static void main(String args[]) {

DiscoveryClient disocveryClient = new DiscoveryClient();disocveryClient.start();

}

// loop forever attempting to discover advertisements every minutepublic void start() {

long waittime = 60 * 1000L;try {

// Add ourselves as a DiscoveryListener for DiscoveryResponse eventsdiscovery.addDiscoveryListener(this);discovery.getRemoteAdvertisements( null, // no specific peer (propagate)

DiscoveryService.ADV, // Adv type

15/12/2008 34

null, // Attribute = anynull, // Value = any1, // one advertisement response is all we are looking fornull);// no query specific listener. we are using a global listener

while (true) { // wait a bit before sending a discovery messagetry {

System.out.println("Sleeping for :" + waittime);Thread.sleep(waittime);

} catch (Exception e) { // ignored }System.out.println("Sending a Discovery Message");

discovery.getRemoteAdvertisements( null, DiscoveryService.ADV, null, null, 1, null );}

} catch (Exception e) {e.printStackTrace();

}}

DiscoveryDiscovery (Client)(Client)

public void discoveryEvent(DiscoveryEvent ev) {DiscoveryResponseMsg res = ev.getResponse();// let's get the responding peer's advertisementSystem.out.println(" [ Got a Discovery Response [" + res.getResponseCount() + " elements] from peer : " +

ev.getSource() + " ]");Advertisement adv;Enumeration en = res.getAdvertisements();if (en != null) {

while (en hasMoreElements()) {

15/12/2008 35

while (en.hasMoreElements()) {adv = (Advertisement) en.nextElement();System.out.println(adv);

}}

}

/*** Stops the platform*/public void stop() {

// Stop JXTAmanager.stopNetwork();

}

DemoDemo

Page 7: Lezione 9 - UNISAcordasco/teaching/ASDAD0809/lezione9.pdf · 15/12/2008 3 Le vostre domande yOrali? Tutti i venerdì dal 16 Gennaioa fine Febbraio (max 6 su prenotazione). Tuttipossono

15/12/2008

7

Pipe (Server)Pipe (Server)import net.jxta.document.MimeMediaType;import net.jxta.endpoint.Message;import net.jxta.endpoint.Message.ElementIterator;import net.jxta.endpoint.MessageElement;import net.jxta.endpoint.WireFormatMessage;import net.jxta.endpoint.WireFormatMessageFactory;import net.jxta.peergroup.PeerGroup;import net.jxta.pipe.InputPipe;import net.jxta.pipe.PipeMsgEvent;import net.jxta.pipe.PipeMsgListener;import net.jxta.pipe.PipeService;import net.jxta.platform.NetworkManager;import net.jxta.protocol.PipeAdvertisement;import net.jxta.util.CountingOutputStream;import net.jxta.util.DevNullOutputStream;import java.io.File;import java.io.IOException;import java.util.Date;

15/12/2008 37

public class PipeServer implements PipeMsgListener {static PeerGroup netPeerGroup = null;transient NetworkManager manager;private PipeService pipeService;private PipeAdvertisement pipeAdv;private InputPipe inputPipe = null;public PipeServer() {

manager = null;try {

manager = new net.jxta.platform.NetworkManager(NetworkManager.ConfigMode.EDGE, "PipeServer",new File(new File(".cache"), "PipeServer").toURI());

manager.startNetwork();} catch (Exception e) {}

netPeerGroup = manager.getNetPeerGroup(); // Get the NetPeerGrouppipeService = netPeerGroup.getPipeService(); // get the pipe service, and discoverypipeAdv = PipeClient.getPipeAdvertisement(); // create the pipe advertisement

Pipe (Server)Pipe (Server)public static void main(String args[]) {

PipeServer server = new PipeServer();server.start();

}

// Creates the input pipe with this as the message listener

public void start() {try {

System.out.println("Creating input pipe");// Create the InputPipe and register this for message arrival

15/12/2008 38

// Create the InputPipe and register this for message arrival// notification call-backinputPipe = pipeService.createInputPipe(pipeAdv, this);

} catch (IOException io) {io.printStackTrace();return;

}if (inputPipe == null) {

System.out.println(" cannot open InputPipe");System.exit(-1);

}System.out.println("Waiting for msgs on input pipe");

}

Pipe (Server)Pipe (Server)public void pipeMsgEvent(PipeMsgEvent event) {

Message msg;try {

msg = event.getMessage(); // Obtain the message from the eventif (msg == null) {

System.out.println("Received an empty message");return;

}printMessageStats(msg, true); // dump the message content to screen

} catch (Exception e) { e.printStackTrace(); return; }Message.ElementIterator en = msg.getMessageElements();if (!en hasNext()) {

15/12/2008 39

if (!en.hasNext()) {return;

}// get the message element in the name space PipeClient.MESSAGE_NAME_SPACEMessageElement msgElement = msg.getMessageElement(null,

PipeClient.MESSAGE_NAME_SPACE);// Get messageif (msgElement.toString() == null) { System.out.println("null msg received");} else {

Date date = new Date(System.currentTimeMillis());System.out.println("Message received at :" + date.toString());System.out.println("Message created at :" + msgElement.toString());

}}

Pipe (Server)Pipe (Server)public static void printMessageStats(Message msg, boolean verbose) {

try {CountingOutputStream cnt;ElementIterator it = msg.getMessageElements();System.out.println("------------------Begin Message---------------------");WireFormatMessage serialed = WireFormatMessageFactory.toWire(msg, new

MimeMediaType("application/x-jxta-msg"), null);System.out.println("Message Size :" + serialed.getByteLength());while (it.hasNext()) {

MessageElement el = it.next();String eName = el.getElementName();cnt = new CountingOutputStream(new DevNullOutputStream());

15/12/2008 40

g p ( p ());el.sendToStream(cnt);long size = cnt.getBytesWritten();System.out.println("Element " + eName + " : " + size);if (verbose) {

System.out.println("[" + el + "]");}

}System.out.println("-------------------End Message----------------------");

} catch (Exception e) { e.printStackTrace(); }}

public void stop() {inputPipe.close(); // Close the input pipemanager.stopNetwork(); // Stop JXTA

}

Pipe (Client)Pipe (Client)import net.jxta.document.AdvertisementFactory;import net.jxta.endpoint.Message;import net.jxta.endpoint.StringMessageElement;import net.jxta.id.IDFactory;import net.jxta.pipe.OutputPipe;import net.jxta.pipe.OutputPipeEvent;import net.jxta.pipe.OutputPipeListener;import net.jxta.pipe.PipeID;import net.jxta.pipe.PipeService;import net.jxta.platform.NetworkManager;import net.jxta.protocol.PipeAdvertisement;

import java.io.File;import java.io.IOException;import java.net.URI;import java.net.URISyntaxException;import java.util.Date;

15/12/2008 41

public class PipeClient implements OutputPipeListener {public final static String MESSAGE_NAME_SPACE = "PipeTutorial";private boolean waitForRendezvous = false;private PipeService pipeService;private PipeAdvertisement pipeAdv;private OutputPipe outputPipe;private final Object lock = new Object();private NetworkManager manager;public final static String PIPEIDSTR = "urn:jxta:uuid-

59616261646162614E50472050325033C0C1DE89719B456691A596B983BA0E1004";

Pipe (Client)Pipe (Client)public PipeClient(boolean waitForRendezvous) {

this.waitForRendezvous = waitForRendezvous;try {

manager = newnet.jxta.platform.NetworkManager(NetworkManager.ConfigMode.EDGE, "PipeClient",

new File(new File(".cache"), "PipeClient").toURI());manager.startNetwork();

} catch (Exception e) {e.printStackTrace();System.exit(-1);

}pipeService = manager.getNetPeerGroup().getPipeService(); // get the pipe service

15/12/2008 42

p p g g p() g p (); g p ppipeAdv = getPipeAdvertisement(); // create the pipe advertisement

}

public static void main(String args[]) {// by setting this property it will trigger a wait for a rendezvous// connection prior to attempting to resolve the pipeString value = System.getProperty("RDVWAIT", "false");boolean waitForRendezvous = Boolean.valueOf(value);PipeClient client = new PipeClient(waitForRendezvous);client.start();

}

Page 8: Lezione 9 - UNISAcordasco/teaching/ASDAD0809/lezione9.pdf · 15/12/2008 3 Le vostre domande yOrali? Tutti i venerdì dal 16 Gennaioa fine Febbraio (max 6 su prenotazione). Tuttipossono

15/12/2008

8

Pipe (Client)Pipe (Client)public static PipeAdvertisement getPipeAdvertisement() {

PipeID pipeID = null;try {

pipeID = (PipeID) IDFactory.fromURI(new URI(PIPEIDSTR));} catch (URISyntaxException use) { use.printStackTrace(); }PipeAdvertisement advertisement = (PipeAdvertisement)

AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());advertisement.setPipeID(pipeID);advertisement.setType(PipeService.UnicastType);advertisement.setName("Pipe tutorial");return advertisement;

}

15/12/2008 43

}

public synchronized void start() {try {

if (waitForRendezvous) {manager.waitForRendezvousConnection(0);

}pipeService.createOutputPipe(pipeAdv, this);try {

synchronized (lock) {lock.wait();

}} catch (InterruptedException e) { System.out.println("Thread interrupted"); }

} catch (IOException e) { System.out.println("OutputPipe creation failure"); }}

Pipe (Client)Pipe (Client)public void outputPipeEvent(OutputPipeEvent event) {

System.out.println("Received the output pipe resolution event");outputPipe = event.getOutputPipe();Message msg;try {

System.out.println("Sending message");msg = new Message(); // create the messageDate date = new Date(System.currentTimeMillis());StringMessageElement sme = new StringMessageElement(MESSAGE_NAME_SPACE,

date.toString(), null);msg.addMessageElement(null, sme);outputPipe.send(msg);

15/12/2008 44

p p ( g);System.out.println("message sent");

} catch (IOException e) { System.out.println("failed to send message"); }stop();

}

public void stop() {outputPipe.close();// Stop JXTAmanager.stopNetwork();synchronized (lock) {

// done.lock.notify();

}}

DemoDemoSocketSocket (Server)(Server)import net.jxta.document.AdvertisementFactory;import net.jxta.id.IDFactory;import net.jxta.pipe.PipeID;import net.jxta.pipe.PipeService;import net.jxta.platform.NetworkManager;import net.jxta.protocol.PipeAdvertisement;import net.jxta.socket.JxtaMulticastSocket;import java.io.File;import java.io.IOException;import java.net.DatagramPacket;import java.net.URI;import java.net.URISyntaxException;

public class JxtaMulticastSocketServer {public final static String SOCKETIDSTR = "urn:jxta:uuid-

15/12/2008 46

p g j59616261646162614E5047205032503393B5C2F6CA7A41FDB0F890173088E79404";

public static PipeAdvertisement getSocketAdvertisement() {PipeID socketID = null;try {

socketID = (PipeID) IDFactory.fromURI(new URI(SOCKETIDSTR));} catch (URISyntaxException use) { use.printStackTrace(); }PipeAdvertisement advertisement = (PipeAdvertisement)

AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());advertisement.setPipeID(socketID);advertisement.setType(PipeService.PropagateType);advertisement.setName("Socket tutorial");return advertisement;

}

SocketSocket (Server)(Server)public static void main(String args[]) {

net.jxta.platform.NetworkManager manager = null;try {

manager = new net.jxta.platform.NetworkManager(NetworkManager.ConfigMode.EDGE, "JxtaMulticastSocketServer", new File(new File(".cache"), "JxtaMulticastSocketServer").toURI());

manager.startNetwork();} catch (Exception e) { e.printStackTrace(); }System.out.println("Creating JxtaMulticastSocket");JxtaMulticastSocket mcastSocket = null;try {

mcastSocket = new JxtaMulticastSocket(manager.getNetPeerGroup(), getSocketAdvertisement());System.out.println("LocalAddress :" + mcastSocket.getLocalAddress());System.out.println("LocalSocketAddress :" + mcastSocket.getLocalSocketAddress());

} catch (IOException e) { e printStackTrace(); }

15/12/2008 47

} catch (IOException e) { e.printStackTrace(); }

byte[] buffer = new byte[16384];String ten4 = "Ten 4";

DatagramPacket packet = new DatagramPacket(buffer, buffer.length);try { // wait for a datagram. The following can be put into a loop

mcastSocket.receive(packet);String sw = new String(packet.getData(), 0, packet.getLength());System.out.println("Received data from :" + packet.getAddress());System.out.println(sw);DatagramPacket res = new DatagramPacket(ten4.getBytes(), ten4.length());res.setAddress(packet.getAddress());mcastSocket.send(res);

} catch (IOException e) { e.printStackTrace(); }}

SocketSocket (Client)(Client)import net.jxta.peergroup.PeerGroup;import net.jxta.platform.NetworkManager;import net.jxta.socket.JxtaMulticastSocket;import java.io.File;import java.io.IOException;import java.net.DatagramPacket;import java.util.Date;public class JxtaMulticastSocketClient {

public static void main(String args[]) {NetworkManager manager = null;

try {

15/12/2008 48

y {manager = new net.jxta.platform.NetworkManager(NetworkManager.ConfigMode.EDGE,

"JxtaMulticastSocketClient", new File(new File(".cache"), "JxtaMulticastSocketClient").toURI());manager.startNetwork();

} catch (Exception e) { e.printStackTrace(); }PeerGroup netPeerGroup = manager.getNetPeerGroup();JxtaMulticastSocket mcastSocket = null;try {

mcastSocket = new JxtaMulticastSocket(netPeerGroup, JxtaMulticastSocketServer.getSocketAdvertisement());

} catch (IOException e) { e.printStackTrace(); }Date date = new Date(System.currentTimeMillis());String hello = "Hello on : " + date.toString();

Page 9: Lezione 9 - UNISAcordasco/teaching/ASDAD0809/lezione9.pdf · 15/12/2008 3 Le vostre domande yOrali? Tutti i venerdì dal 16 Gennaioa fine Febbraio (max 6 su prenotazione). Tuttipossono

15/12/2008

9

SocketSocket (Client)(Client)

try {DatagramPacket packet = new DatagramPacket(hello.getBytes(), hello.length());mcastSocket.send(packet);byte[] res = new byte[16384];DatagramPacket rpacket = new DatagramPacket(res, res.length);// It's likely we'll receive 2 packets a loopback and a response// loopbackmcastSocket.receive(rpacket);// server response

15/12/2008 49

mcastSocket.receive(rpacket);String sw = new String(rpacket.getData(), 0, rpacket.getLength());System.out.println("Received data from :" + rpacket.getAddress());System.out.println(sw);// stop the platformmanager.stopNetwork();

} catch (IOException e) {e.printStackTrace();

}}

DemoDemo

15/12/2008 51

Grazie per l’attenzione


Recommended