41
Programming with JXTA Programming with JXTA Sending Messages Between two Sending Messages Between two Peers Peers JxtaBiDiPipe JxtaBiDiPipe JxtaSockets JxtaSockets

Programming with JXTA

  • Upload
    jody

  • View
    19

  • Download
    0

Embed Size (px)

DESCRIPTION

Programming with JXTA. Sending Messages Between two Peers JxtaBiDiPipe JxtaSockets. Programming with JXTA. Devono avere home directory diverse. Sending Messages Between two Peers Due programmi Pipe Listner Crea una input pipe (usando l’advertisement examplepipe.adv) - PowerPoint PPT Presentation

Citation preview

Page 1: Programming with JXTA

Programming with JXTAProgramming with JXTA

Sending Messages Between two PeersSending Messages Between two Peers

JxtaBiDiPipeJxtaBiDiPipe

JxtaSocketsJxtaSockets

Page 2: Programming with JXTA

Sending Messages Between two PeersSending Messages Between two Peers Due programmiDue programmi

Pipe ListnerPipe Listner Crea una input pipe (usando l’advertisement Crea una input pipe (usando l’advertisement

examplepipe.adv)examplepipe.adv) Pubblica l’advertisement della pipe (nell’esempio Pubblica l’advertisement della pipe (nell’esempio

assumiamo che l’advertisement è stato inviato assumiamo che l’advertisement è stato inviato precedentemente)precedentemente)

Attende messaggiAttende messaggi

Pipe ExamplePipe Example Crea una output pipe (usando l’advertisement Crea una output pipe (usando l’advertisement

examplepipe.adv)examplepipe.adv) Invia un messaggioInvia un messaggio

Programming with JXTAProgramming with JXTA

Devono avere home directory

diverse

Page 3: Programming with JXTA

import java.io.FileInputStream;import java.io.FileInputStream;import java.util.Date;import java.util.Date;import java.util.Enumeration;import java.util.Enumeration;import net.jxta.document.AdvertisementFactory;import net.jxta.document.AdvertisementFactory;import net.jxta.document.MimeMediaType;import net.jxta.document.MimeMediaType;import net.jxta.endpoint.Message;import net.jxta.endpoint.Message;import net.jxta.endpoint.MessageElement;import net.jxta.endpoint.MessageElement;import net.jxta.endpoint.WireFormatMessage;import net.jxta.endpoint.WireFormatMessage;import net.jxta.endpoint.WireFormatMessageFactory;import net.jxta.endpoint.WireFormatMessageFactory;import net.jxta.endpoint.Message.ElementIterator;import net.jxta.endpoint.Message.ElementIterator;import net.jxta.exception.PeerGroupException;import net.jxta.exception.PeerGroupException;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroupFactory;import net.jxta.peergroup.PeerGroupFactory;import net.jxta.pipe.InputPipe;import net.jxta.pipe.InputPipe;import net.jxta.pipe.PipeMsgEvent;import net.jxta.pipe.PipeMsgEvent;import net.jxta.pipe.PipeMsgListener;import net.jxta.pipe.PipeMsgListener;import net.jxta.pipe.PipeService;import net.jxta.pipe.PipeService;import net.jxta.protocol.PipeAdvertisement;import net.jxta.protocol.PipeAdvertisement;import net.jxta.util.CountingOutputStream;import net.jxta.util.CountingOutputStream;import net.jxta.util.DevNullOutputStream;import net.jxta.util.DevNullOutputStream;

Programming with JXTAProgramming with JXTA

public class PipeListener implements PipeMsgListener public class PipeListener implements PipeMsgListener {{

static PeerGroup netPeerGroup = null;static PeerGroup netPeerGroup = null; private PipeService pipe;private PipeService pipe; private PipeAdvertisement pipeAdv;private PipeAdvertisement pipeAdv; private InputPipe pipeIn = null;private InputPipe pipeIn = null; private final static String SenderMessage = private final static String SenderMessage =

"PipeListenerMsg";"PipeListenerMsg";

public static void main(String args[]) {public static void main(String args[]) { PipeListener myapp = new PipeListener();PipeListener myapp = new PipeListener(); myapp.startJxta();myapp.startJxta(); myapp.run();myapp.run(); }}

Pipe ListnerPipe Listner

Page 4: Programming with JXTA

private void startJxta() {private void startJxta() { try {try {

netPeerGroup=PeerGroupFactory.newNetPeerGroup();netPeerGroup=PeerGroupFactory.newNetPeerGroup();}}

catch (PeerGroupException e) {catch (PeerGroupException e) { System.out.println("fatal error : group creation failure");System.out.println("fatal error : group creation failure");

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

pipe = netPeerGroup.getPipeService();pipe = netPeerGroup.getPipeService(); System.out.println("Reading in pipexample.adv");System.out.println("Reading in pipexample.adv"); try {try { FileInputStream is = new FileInputStream("pipexample.adv");FileInputStream is = new FileInputStream("pipexample.adv"); pipeAdv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is);pipeAdv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is); is.close();is.close(); } catch (Exception e) {} catch (Exception e) { System.out.println("failed to read/parse pipe advertisement");System.out.println("failed to read/parse pipe advertisement"); e.printStackTrace();e.printStackTrace(); System.exit(-1);System.exit(-1); }} }}

Programming with JXTAProgramming with JXTA

Pipe ListnerPipe Listner

Page 5: Programming with JXTA

public void run() {public void run() { try {try { System.out.println("Creating input pipe");System.out.println("Creating input pipe"); pipeIn = pipe.createInputPipe(pipeAdv, this);pipeIn = pipe.createInputPipe(pipeAdv, this); } catch (Exception e) {} catch (Exception e) { return;return; }} if (pipeIn == null) {if (pipeIn == null) { System.out.println(" cannot open InputPipe");System.out.println(" cannot open InputPipe"); System.exit(-1);System.exit(-1); }} System.out.println("Waiting for msgs on input pipe");System.out.println("Waiting for msgs on input pipe"); }}

Programming with JXTAProgramming with JXTA

Pipe ListnerPipe Listner

Page 6: Programming with JXTA

public void pipeMsgEvent(PipeMsgEvent event) {public void pipeMsgEvent(PipeMsgEvent event) { Message msg=null;Message msg=null; try {// grab the message from the eventtry {// grab the message from the event

msg = event.getMessage();msg = event.getMessage(); if (msg == null) { return;if (msg == null) { return; }} printMessageStats(msg, true);printMessageStats(msg, true); } catch (Exception e) {} catch (Exception e) { e.printStackTrace();e.printStackTrace(); return;return; }} // get all the message elements// get all the message elements Message.ElementIterator en = msg.getMessageElements();Message.ElementIterator en = msg.getMessageElements(); if (!en.hasNext()) { return;if (!en.hasNext()) { return; }} // get the message element named SenderMessage// get the message element named SenderMessage MessageElement msgElement = msg.getMessageElement(null, SenderMessage);MessageElement msgElement = msg.getMessageElement(null, SenderMessage); // Get message// Get message if (msgElement.toString() == null) {if (msgElement.toString() == null) { System.out.println("null msg received");System.out.println("null msg received"); } else {} else { Date date = new Date(System.currentTimeMillis());Date date = new Date(System.currentTimeMillis()); System.out.println("Message received at :"+ date.toString());System.out.println("Message received at :"+ date.toString()); System.out.println("Message created at :"+ msgElement.toString());System.out.println("Message created at :"+ msgElement.toString()); }} }}

Programming with JXTAProgramming with JXTA

Pipe ListnerPipe Listner

namespace

Page 7: Programming with JXTA

public static void printMessageStats(Message msg, boolean verbose) {public static void printMessageStats(Message msg, boolean verbose) { try {try { CountingOutputStream cnt;CountingOutputStream cnt; ElementIterator it = msg.getMessageElements();ElementIterator it = msg.getMessageElements(); System.out.println("------------------Begin Message---------------------");System.out.println("------------------Begin Message---------------------"); WireFormatMessage serialed = WireFormatMessageFactory.toWire( msg,WireFormatMessage serialed = WireFormatMessageFactory.toWire( msg, new MimeMediaType("application/x-jxta-msg"), (MimeMediaType[]) null);new MimeMediaType("application/x-jxta-msg"), (MimeMediaType[]) null); System.out.println("Message Size :" + serialed.getByteLength());System.out.println("Message Size :" + serialed.getByteLength()); while (it.hasNext()) {while (it.hasNext()) { MessageElement el = (MessageElement) it.next();MessageElement el = (MessageElement) it.next(); String eName = el.getElementName();String eName = el.getElementName(); cnt = new CountingOutputStream(new DevNullOutputStream());cnt = new CountingOutputStream(new DevNullOutputStream()); el.sendToStream(cnt);el.sendToStream(cnt); long size = cnt.getBytesWritten();long size = cnt.getBytesWritten(); System.out.println("Element " + eName + " : " + size);System.out.println("Element " + eName + " : " + size); if (verbose) {if (verbose) { System.out.println("["+el+"]");System.out.println("["+el+"]"); }} }} System.out.println("-------------------End Message----------------------");System.out.println("-------------------End Message----------------------"); } catch (Exception e) {} catch (Exception e) { System.out.println("Errore");System.out.println("Errore"); e.printStackTrace();e.printStackTrace();

}} }}

Programming with JXTAProgramming with JXTA

Pipe ListnerPipe Listner

Page 8: Programming with JXTA

import java.io.FileInputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.IOException;import java.util.Date;import java.util.Date;

import net.jxta.discovery.DiscoveryService;import net.jxta.discovery.DiscoveryService;import net.jxta.document.AdvertisementFactory;import net.jxta.document.AdvertisementFactory;import net.jxta.document.MimeMediaType;import net.jxta.document.MimeMediaType;import net.jxta.endpoint.Message;import net.jxta.endpoint.Message;import net.jxta.endpoint.StringMessageElement;import net.jxta.endpoint.StringMessageElement;import net.jxta.exception.PeerGroupException;import net.jxta.exception.PeerGroupException;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroupFactory;import net.jxta.peergroup.PeerGroupFactory;import net.jxta.pipe.OutputPipe;import net.jxta.pipe.OutputPipe;import net.jxta.pipe.OutputPipeEvent;import net.jxta.pipe.OutputPipeEvent;import net.jxta.pipe.OutputPipeListener;import net.jxta.pipe.OutputPipeListener;import net.jxta.pipe.PipeService;import net.jxta.pipe.PipeService;import net.jxta.protocol.PipeAdvertisement;import net.jxta.protocol.PipeAdvertisement;import net.jxta.rendezvous.RendezvousEvent;import net.jxta.rendezvous.RendezvousEvent;import net.jxta.rendezvous.RendezvousListener;import net.jxta.rendezvous.RendezvousListener;import net.jxta.rendezvous.RendezVousService;import net.jxta.rendezvous.RendezVousService;

Programming with JXTAProgramming with JXTA

public class PipeExample implementspublic class PipeExample implements Runnable,Runnable, OutputPipeListener,OutputPipeListener, RendezvousListener {RendezvousListener {

static PeerGroup netPeerGroup = null;static PeerGroup netPeerGroup = null; private final static String SenderMessage = private final static String SenderMessage = "PipeListenerMsg";"PipeListenerMsg"; private PipeService pipe;private PipeService pipe; private DiscoveryService discovery;private DiscoveryService discovery; private PipeAdvertisement pipeAdv;private PipeAdvertisement pipeAdv; private RendezVousService rendezvous;private RendezVousService rendezvous;

public static void main(String args[]) {public static void main(String args[]) { PipeExample myapp = new PipeExample();PipeExample myapp = new PipeExample(); myapp.startJxta();myapp.startJxta(); myapp.run();myapp.run(); }}

PipeExamplePipeExample

Page 9: Programming with JXTA

private void startJxta() {private void startJxta() { try { // create, and Start the default jxta NetPeerGrouptry { // create, and Start the default jxta NetPeerGroup netPeerGroup = PeerGroupFactory.newNetPeerGroup();netPeerGroup = PeerGroupFactory.newNetPeerGroup(); rendezvous = netPeerGroup.getRendezVousService();rendezvous = netPeerGroup.getRendezVousService(); rendezvous.addListener(this);rendezvous.addListener(this);

} catch (PeerGroupException e) { // could not instantiate the group, print the stack and exit} catch (PeerGroupException e) { // could not instantiate the group, print the stack and exit System.out.println("fatal error : group creation failure");System.out.println("fatal error : group creation failure"); e.printStackTrace();e.printStackTrace(); System.exit(-1);System.exit(-1); }} // get the pipe service, and discovery// get the pipe service, and discovery pipe = netPeerGroup.getPipeService();pipe = netPeerGroup.getPipeService(); discovery = netPeerGroup.getDiscoveryService();discovery = netPeerGroup.getDiscoveryService(); System.out.println("Reading in pipexample.adv");System.out.println("Reading in pipexample.adv"); try {try { FileInputStream is = new FileInputStream("pipexample.adv");FileInputStream is = new FileInputStream("pipexample.adv"); pipeAdv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is);pipeAdv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is); is.close();is.close(); } catch (Exception e) {} catch (Exception e) { System.out.println("failed to read/parse pipe advertisement");System.out.println("failed to read/parse pipe advertisement"); e.printStackTrace();e.printStackTrace(); System.exit(-1);System.exit(-1); }} }}

Programming with JXTAProgramming with JXTA

PipeExamplePipeExample

Page 10: Programming with JXTA

public synchronized void run() {public synchronized void run() { try { // this step helps when running standalone (local sub-net without any redezvous setup)try { // this step helps when running standalone (local sub-net without any redezvous setup) discovery.getRemoteAdvertisements(null, DiscoveryService.ADV, null, null, 1, null);discovery.getRemoteAdvertisements(null, DiscoveryService.ADV, null, null, 1, null); // create output pipe with asynchronously// create output pipe with asynchronously // Send out the first pipe resolve call// Send out the first pipe resolve call System.out.println("Attempting to create a OutputPipe");System.out.println("Attempting to create a OutputPipe"); pipe.createOutputPipe(pipeAdv, this);pipe.createOutputPipe(pipeAdv, this); // send out a second pipe resolution after we connect to a rendezvous// send out a second pipe resolution after we connect to a rendezvous if (!rendezvous.isConnectedToRendezVous()) {if (!rendezvous.isConnectedToRendezVous()) { System.out.println("Waiting for Rendezvous Connection");System.out.println("Waiting for Rendezvous Connection"); try {try { wait();wait(); System.out.println("Connected to Rendezvous, attempting to create a OutputPipe");System.out.println("Connected to Rendezvous, attempting to create a OutputPipe"); pipe.createOutputPipe(pipeAdv, this);pipe.createOutputPipe(pipeAdv, this); } catch (InterruptedException e) {} catch (InterruptedException e) { // got our notification// got our notification }} }} } catch (IOException e) {} catch (IOException e) { System.out.println("OutputPipe creation failure");System.out.println("OutputPipe creation failure"); e.printStackTrace();e.printStackTrace(); System.exit(-1);System.exit(-1); }} }}

Programming with JXTAProgramming with JXTA

PipeExamplePipeExample

Page 11: Programming with JXTA

public void outputPipeEvent(OutputPipeEvent event) {public void outputPipeEvent(OutputPipeEvent event) { System.out.println(" Got an output pipe event");System.out.println(" Got an output pipe event"); OutputPipe op = event.getOutputPipe();OutputPipe op = event.getOutputPipe(); Message msg = null;Message msg = null; try {try { System.out.println("Sending message");System.out.println("Sending message"); msg = new Message();msg = new Message(); Date date = new Date(System.currentTimeMillis());Date date = new Date(System.currentTimeMillis()); StringMessageElement sme = new StringMessageElement(SenderMessage, StringMessageElement sme = new StringMessageElement(SenderMessage,

date.toString() , null);date.toString() , null); msg.addMessageElement(null, sme);msg.addMessageElement(null, sme); op.send(msg);op.send(msg); } catch (IOException e) {} catch (IOException e) { System.out.println("failed to send message");System.out.println("failed to send message"); e.printStackTrace();e.printStackTrace(); System.exit(-1);System.exit(-1); }} op.close();op.close(); System.out.println("message sent");System.out.println("message sent"); }}

Programming with JXTAProgramming with JXTA

PipeExamplePipeExample

Page 12: Programming with JXTA

public synchronized void rendezvousEvent(RendezvousEvent event) public synchronized void rendezvousEvent(RendezvousEvent event) {{

if (event.getType() == event.RDVCONNECT ||if (event.getType() == event.RDVCONNECT ||

event.getType() == event.RDVRECONNECT ) {event.getType() == event.RDVRECONNECT ) {

notify();notify();

}}

}}

Programming with JXTAProgramming with JXTA

PipeExamplePipeExample

Thread (metodo run())

Page 13: Programming with JXTA

DemoDemo

Sending Messages Between two PeersSending Messages Between two Peers

Page 14: Programming with JXTA

JxtaBiDiPipeJxtaBiDiPipe JxtaServerPipe definisce una serie di metodiJxtaServerPipe definisce una serie di metodi

bind: lega la pipe al gruppobind: lega la pipe al gruppo

connect: connette la pipe al JxtaServerPipeconnect: connette la pipe al JxtaServerPipe

setPipeTimeoutsetPipeTimeout

setReliablesetReliable

setListnersetListner

sendMessage sendMessage

getMessagegetMessage

Programming with JXTAProgramming with JXTA

Page 15: Programming with JXTA

JxtaBiDiPipeJxtaBiDiPipe Due programmiDue programmi

JxtaServerPipeExampleJxtaServerPipeExample Crea una bidi pipe (usando l’advertisement pipe.adv)Crea una bidi pipe (usando l’advertisement pipe.adv) Pubblica l’advertisement della pipe (nell’esempio Pubblica l’advertisement della pipe (nell’esempio

assumiamo che l’advertisement è stato inviato assumiamo che l’advertisement è stato inviato precedentemente)precedentemente)

Attende messaggiAttende messaggi

JxtaBiDiPipeExampleJxtaBiDiPipeExample Si connette alla pipe e riceve 100 messaggiSi connette alla pipe e riceve 100 messaggi

Programming with JXTAProgramming with JXTA

Devono avere home directory

diverse

Page 16: Programming with JXTA

import java.io.File;import java.io.File;import java.io.FileOutputStream;import java.io.FileOutputStream;import java.io.FileInputStream;import java.io.FileInputStream;import java.io.InputStream;import java.io.InputStream;import java.io.IOException;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStream;import java.util.Date;import java.util.Date;import net.jxta.credential.AuthenticationCredential;import net.jxta.credential.AuthenticationCredential;import net.jxta.credential.Credential;import net.jxta.credential.Credential;import net.jxta.document.AdvertisementFactory;import net.jxta.document.AdvertisementFactory;import net.jxta.document.MimeMediaType;import net.jxta.document.MimeMediaType;import net.jxta.endpoint.Message;import net.jxta.endpoint.Message;import net.jxta.endpoint.MessageElement;import net.jxta.endpoint.MessageElement;import net.jxta.endpoint.Messenger;import net.jxta.endpoint.Messenger;import net.jxta.endpoint.StringMessageElement;import net.jxta.endpoint.StringMessageElement;import net.jxta.exception.PeerGroupException;import net.jxta.exception.PeerGroupException;import net.jxta.membership.InteractiveAuthenticator;import net.jxta.membership.InteractiveAuthenticator;import net.jxta.membership.MembershipService;import net.jxta.membership.MembershipService;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroupFactory;import net.jxta.peergroup.PeerGroupFactory;import net.jxta.protocol.PipeAdvertisement;import net.jxta.protocol.PipeAdvertisement;import net.jxta.util.JxtaBiDiPipe;import net.jxta.util.JxtaBiDiPipe;import net.jxta.util.JxtaServerPipe;import net.jxta.util.JxtaServerPipe;import net.jxta.document.MimeMediaType;import net.jxta.document.MimeMediaType;import net.jxta.document.StructuredDocument;import net.jxta.document.StructuredDocument;import net.jxta.impl.protocol.PlatformConfig;import net.jxta.impl.protocol.PlatformConfig;import org.apache.log4j.Logger;import org.apache.log4j.Logger;

Programming with JXTAProgramming with JXTAJxtaServerPipeExampleJxtaServerPipeExample

Page 17: Programming with JXTA

Programming with JXTAProgramming with JXTApublic class JxtaServerPipeExample {public class JxtaServerPipeExample { public static final int ITERATIONS = 100;public static final int ITERATIONS = 100; private PeerGroup netPeerGroup = null;private PeerGroup netPeerGroup = null; private PipeAdvertisement pipeAdv;private PipeAdvertisement pipeAdv; private JxtaServerPipe serverPipe;private JxtaServerPipe serverPipe; private static final MimeMediaType MEDIA_TYPE = new MimeMediaType("application/bin");private static final MimeMediaType MEDIA_TYPE = new MimeMediaType("application/bin"); private final static Logger LOG = Logger.getLogger(JxtaServerPipeExample.class.getName());private final static Logger LOG = Logger.getLogger(JxtaServerPipeExample.class.getName()); private final static String SenderMessage = "pipe_tutorial";private final static String SenderMessage = "pipe_tutorial";

public static void main(String args[]) {public static void main(String args[]) { JxtaServerPipeExample eg = new JxtaServerPipeExample();JxtaServerPipeExample eg = new JxtaServerPipeExample(); eg.startJxta();eg.startJxta(); System.out.println("Reading in pipe.adv");System.out.println("Reading in pipe.adv"); try {try { FileInputStream is = new FileInputStream("pipe.adv");FileInputStream is = new FileInputStream("pipe.adv"); eg.pipeAdv = (PipeAdvertisement) eg.pipeAdv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is);AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is); is.close();is.close(); eg.serverPipe = new JxtaServerPipe(eg.netPeerGroup, eg.pipeAdv);eg.serverPipe = new JxtaServerPipe(eg.netPeerGroup, eg.pipeAdv); eg.serverPipe.setPipeTimeout(0); // we want to block until a connection is establishedeg.serverPipe.setPipeTimeout(0); // we want to block until a connection is established } catch (Exception e) {} catch (Exception e) { System.out.println("failed to bind to the JxtaServerPipe due to the following exception");System.out.println("failed to bind to the JxtaServerPipe due to the following exception"); e.printStackTrace();e.printStackTrace(); System.exit(-1);System.exit(-1); }} eg.run();eg.run(); }}

JxtaServerPipeExampleJxtaServerPipeExample

Page 18: Programming with JXTA

Programming with JXTAProgramming with JXTA

private void startJxta() {private void startJxta() { try {try { System.setProperty("net.jxta.tls.principal", "server");System.setProperty("net.jxta.tls.principal", "server"); System.setProperty("net.jxta.tls.password", "password");System.setProperty("net.jxta.tls.password", "password"); System.setProperty("JXTA_HOME", System.getProperty("JXTA_HOME", "server"));System.setProperty("JXTA_HOME", System.getProperty("JXTA_HOME", "server")); File home = new File(System.getProperty("JXTA_HOME", "server"));File home = new File(System.getProperty("JXTA_HOME", "server")); if (!configured(home)) {if (!configured(home)) { createConfig(home, "JxtaServerPipeExample", true);createConfig(home, "JxtaServerPipeExample", true); }} // create, and Start the default jxta NetPeerGroup// create, and Start the default jxta NetPeerGroup netPeerGroup = PeerGroupFactory.newNetPeerGroup();netPeerGroup = PeerGroupFactory.newNetPeerGroup(); JxtaBidiPipeExample.login(netPeerGroup, "server", "password");JxtaBidiPipeExample.login(netPeerGroup, "server", "password"); } catch (PeerGroupException e) {} catch (PeerGroupException e) { System.out.println("fatal error : group creation failure");System.out.println("fatal error : group creation failure"); e.printStackTrace();e.printStackTrace(); System.exit(1);System.exit(1); }} }}

JxtaServerPipeExampleJxtaServerPipeExample

Page 19: Programming with JXTA

public void run() {public void run() { System.out.println("Waiting for JxtaBidiPipe connections on JxtaServerPipe");System.out.println("Waiting for JxtaBidiPipe connections on JxtaServerPipe"); while (true) {while (true) { try {try { JxtaBiDiPipe bipipe = serverPipe.accept();JxtaBiDiPipe bipipe = serverPipe.accept(); if (bipipe != null ) {if (bipipe != null ) { System.out.println("JxtaBidiPipe accepted, sending 100 messages to the other end") //Send a 100 messagesSystem.out.println("JxtaBidiPipe accepted, sending 100 messages to the other end") //Send a 100 messages sendTestMessages(bipipe);sendTestMessages(bipipe); }} } catch (Exception e) {} catch (Exception e) { e.printStackTrace();e.printStackTrace(); return;return; }} }} }} private void sendTestMessages(JxtaBiDiPipe pipe) {private void sendTestMessages(JxtaBiDiPipe pipe) { try {try { for (int i =0; i<ITERATIONS; i++) {for (int i =0; i<ITERATIONS; i++) { Message msg = new Message();Message msg = new Message(); String data = "Message #"+i;String data = "Message #"+i; msg.addMessageElement(SenderMessage, new StringMessageElement(SenderMessage, data, null));msg.addMessageElement(SenderMessage, new StringMessageElement(SenderMessage, data, null)); System.out.println("Sending :"+data);System.out.println("Sending :"+data); pipe.sendMessage(msg); //Thread.sleep(100);pipe.sendMessage(msg); //Thread.sleep(100); }} } catch (Exception ie) {} catch (Exception ie) { ie.printStackTrace();ie.printStackTrace(); }} }}

Programming with JXTAProgramming with JXTAJxtaServerPipeExampleJxtaServerPipeExample

Page 20: Programming with JXTA

protected static InputStream getResourceInputStream(String resource) throws IOException {protected static InputStream getResourceInputStream(String resource) throws IOException {ClassLoader cl = JxtaServerPipeExample.class.getClassLoader();ClassLoader cl = JxtaServerPipeExample.class.getClassLoader();

return cl.getResourceAsStream(resource);return cl.getResourceAsStream(resource); }}

protected static boolean configured(File home) {protected static boolean configured(File home) { File platformConfig = new File(home, "PlatformConfig");File platformConfig = new File(home, "PlatformConfig"); return platformConfig.exists();return platformConfig.exists(); }}

protected static void createConfig(File home, String name, boolean server) {protected static void createConfig(File home, String name, boolean server) { try {try { String fname = null;String fname = null; if (server) { fname = "ServerPlatformConfig.master";if (server) { fname = "ServerPlatformConfig.master"; } else { fname = "PlatformConfig.master“ }} else { fname = "PlatformConfig.master“ } InputStream is = getResourceInputStream(fname);InputStream is = getResourceInputStream(fname); home.mkdirs();home.mkdirs(); PlatformConfig platformConfig = (PlatformConfig) AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is);PlatformConfig platformConfig = (PlatformConfig) AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is); is.close();is.close(); platformConfig.setName(name);platformConfig.setName(name); File newConfig = new File(home, "PlatformConfig");File newConfig = new File(home, "PlatformConfig"); OutputStream op = new FileOutputStream(newConfig);OutputStream op = new FileOutputStream(newConfig); StructuredDocument doc = (StructuredDocument) platformConfig.getDocument(MimeMediaType.XMLUTF8);StructuredDocument doc = (StructuredDocument) platformConfig.getDocument(MimeMediaType.XMLUTF8); doc.sendToStream(op);doc.sendToStream(op); op.close();op.close(); } catch (IOException e) {} catch (IOException e) { e.printStackTrace();e.printStackTrace(); }} }}

Programming with JXTAProgramming with JXTAJxtaServerPipeExampleJxtaServerPipeExample

Page 21: Programming with JXTA

public class JxtaBidiPipeExample implements PipeMsgListener, RendezvousListener {public class JxtaBidiPipeExample implements PipeMsgListener, RendezvousListener { private PeerGroup netPeerGroup = null;private PeerGroup netPeerGroup = null; private PipeAdvertisement pipeAdv;private PipeAdvertisement pipeAdv; private JxtaBiDiPipe pipe;private JxtaBiDiPipe pipe; private RendezVousService rendezvous;private RendezVousService rendezvous; private final static String SenderMessage = "pipe_tutorial";private final static String SenderMessage = "pipe_tutorial"; private final static String completeLock = "completeLock";private final static String completeLock = "completeLock"; private int count = 0;private int count = 0; private final static Logger LOG = Logger.getLogger(JxtaBidiPipeExample.class.getName());private final static Logger LOG = Logger.getLogger(JxtaBidiPipeExample.class.getName());

private void startJxta() {private void startJxta() { try {try { System.setProperty("net.jxta.tls.principal", "client");System.setProperty("net.jxta.tls.principal", "client"); System.setProperty("net.jxta.tls.password", "password");System.setProperty("net.jxta.tls.password", "password"); System.setProperty("JXTA_HOME", System.getProperty("JXTA_HOME", "client"));System.setProperty("JXTA_HOME", System.getProperty("JXTA_HOME", "client")); File home = new File(System.getProperty("JXTA_HOME", "client"));File home = new File(System.getProperty("JXTA_HOME", "client")); if (!JxtaServerPipeExample.configured(home)) {if (!JxtaServerPipeExample.configured(home)) { JxtaServerPipeExample.createConfig(home, "JxtaBidiPipeExample", false);JxtaServerPipeExample.createConfig(home, "JxtaBidiPipeExample", false); }} // create, and Start the default jxta NetPeerGroup // create, and Start the default jxta NetPeerGroup netPeerGroup = PeerGroupFactory.newNetPeerGroup();netPeerGroup = PeerGroupFactory.newNetPeerGroup(); rendezvous = netPeerGroup.getRendezVousService();rendezvous = netPeerGroup.getRendezVousService(); login(netPeerGroup, "client", "password");login(netPeerGroup, "client", "password"); netPeerGroup.startApp(null);netPeerGroup.startApp(null); } catch (PeerGroupException e) {} catch (PeerGroupException e) { // could not instantiate the group, print the stack and exit// could not instantiate the group, print the stack and exit System.out.println("fatal error : group creation failure");System.out.println("fatal error : group creation failure"); e.printStackTrace();e.printStackTrace(); System.exit(1);System.exit(1); }} }}

Programming with JXTAProgramming with JXTAJxtaBidiPipeExampleJxtaBidiPipeExample

Page 22: Programming with JXTA

public static void main(String args[]) {public static void main(String args[]) { JxtaBidiPipeExample eg = new JxtaBidiPipeExample();JxtaBidiPipeExample eg = new JxtaBidiPipeExample(); eg.startJxta();eg.startJxta(); System.out.println("reading in pipe.adv");System.out.println("reading in pipe.adv"); try {try { FileInputStream is = new FileInputStream("pipe.adv");FileInputStream is = new FileInputStream("pipe.adv"); eg.pipeAdv = (PipeAdvertisement)eg.pipeAdv = (PipeAdvertisement)

AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is);AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is); is.close();is.close(); System.out.println("creating the BiDi pipe");System.out.println("creating the BiDi pipe"); eg.pipe = new JxtaBiDiPipe();eg.pipe = new JxtaBiDiPipe(); eg.pipe.setReliable(true);eg.pipe.setReliable(true);

System.out.println("Attempting to establish a connection");System.out.println("Attempting to establish a connection"); eg.pipe.connect(eg.netPeerGroup, null, eg.pipeAdv, 180000, eg);eg.pipe.connect(eg.netPeerGroup, null, eg.pipeAdv, 180000, eg);

eg.waitUntilCompleted();eg.waitUntilCompleted(); System.exit(0);System.exit(0); } catch (Exception e) {} catch (Exception e) { System.out.println("failed to bind the JxtaBiDiPipe due to the following exception");System.out.println("failed to bind the JxtaBiDiPipe due to the following exception"); e.printStackTrace();e.printStackTrace(); System.exit(-1);System.exit(-1); }} }}

Programming with JXTAProgramming with JXTAJxtaBidiPipeExampleJxtaBidiPipeExample

Page 23: Programming with JXTA

public static void login(PeerGroup group, String principal, String password) {public static void login(PeerGroup group, String principal, String password) { try {try { StringAuthenticator auth = null;StringAuthenticator auth = null; MembershipService membership = group.getMembershipService();MembershipService membership = group.getMembershipService(); Credential cred = membership.getDefaultCredential();Credential cred = membership.getDefaultCredential(); if (cred == null) {if (cred == null) { AuthenticationCredential authCred = new AuthenticationCredential(group, "StringAuthentication", null);AuthenticationCredential authCred = new AuthenticationCredential(group, "StringAuthentication", null); try {try { auth = (StringAuthenticator) membership.apply(authCred);auth = (StringAuthenticator) membership.apply(authCred); } catch(Exception failed) {;}} catch(Exception failed) {;} if (auth != null) {if (auth != null) { auth.setAuth1_KeyStorePassword(password.toCharArray());auth.setAuth1_KeyStorePassword(password.toCharArray()); auth.setAuth2Identity(group.getPeerID());auth.setAuth2Identity(group.getPeerID()); auth.setAuth3_IdentityPassword(principal.toCharArray());auth.setAuth3_IdentityPassword(principal.toCharArray()); if (auth.isReadyForJoin()) {if (auth.isReadyForJoin()) { membership.join(auth);membership.join(auth); } } }} } } cred = membership.getDefaultCredential();cred = membership.getDefaultCredential(); if (null == cred) {if (null == cred) { AuthenticationCredential authCred = new AuthenticationCredential(group, "InteractiveAuthentication", null);AuthenticationCredential authCred = new AuthenticationCredential(group, "InteractiveAuthentication", null); InteractiveAuthenticator iAuth = (InteractiveAuthenticator) membership.apply(authCred);InteractiveAuthenticator iAuth = (InteractiveAuthenticator) membership.apply(authCred); if (iAuth.interact() && iAuth.isReadyForJoin()) {if (iAuth.interact() && iAuth.isReadyForJoin()) { membership.join(iAuth);membership.join(iAuth); } }} } } catch(Throwable e) {} catch(Throwable e) {

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

} finally {} finally { System.err.flush();System.err.flush(); System.out.flush();System.out.flush(); }} }}

Programming with JXTAProgramming with JXTAJxtaBidiPipeExampleJxtaBidiPipeExample

Page 24: Programming with JXTA

public void pipeMsgEvent(PipeMsgEvent event) {public void pipeMsgEvent(PipeMsgEvent event) { Message msg = null;Message msg = null; try { // grab the message from the eventtry { // grab the message from the event msg = event.getMessage();msg = event.getMessage(); if (msg == null) {if (msg == null) { if (LOG.isEnabledFor(Level.DEBUG)) {if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug("Received an empty message, returning");LOG.debug("Received an empty message, returning"); } return;} return; }} if (LOG.isEnabledFor(Level.DEBUG)) {if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug("Received a response");LOG.debug("Received a response"); } // get the message element named SenderMessage} // get the message element named SenderMessage MessageElement msgElement = msg.getMessageElement(SenderMessage, SenderMessage);MessageElement msgElement = msg.getMessageElement(SenderMessage, SenderMessage);

if (msgElement.toString() == null) {if (msgElement.toString() == null) { System.out.println("null msg received");System.out.println("null msg received"); } else {} else { Date date = new Date(System.currentTimeMillis());Date date = new Date(System.currentTimeMillis()); System.out.println("Message :"+ msgElement.toString());System.out.println("Message :"+ msgElement.toString()); count ++; }count ++; } if (count >= JxtaServerPipeExample.ITERATIONS) {if (count >= JxtaServerPipeExample.ITERATIONS) { synchronized(completeLock) {synchronized(completeLock) { completeLock.notify();completeLock.notify(); } }} } } catch (Exception e) {} catch (Exception e) { if (LOG.isEnabledFor(Level.DEBUG)) {if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug(e);LOG.debug(e); }} return; }return; } }}

Programming with JXTAProgramming with JXTA

JxtaBidiPipeExampleJxtaBidiPipeExample

Page 25: Programming with JXTA

DemoDemo

JxtaBiDiPipeJxtaBiDiPipe

Page 26: Programming with JXTA

JxtaSocketsJxtaSockets I JxtaSockets si basano sulle pipe unidirezionali e si I JxtaSockets si basano sulle pipe unidirezionali e si

comportano quasi come i socket java tranne:comportano quasi come i socket java tranne: non implementano l’algoritmo di Nagelnon implementano l’algoritmo di Nagel

non utilizzano keep alive messagesnon utilizzano keep alive messages Due programmiDue programmi

JxtaServerSocketExampleJxtaServerSocketExample Crea il socketCrea il socket Attende connessione e rispondeAttende connessione e risponde

JxtaSocketExampleJxtaSocketExample Si connette al socket e invia messaggiSi connette al socket e invia messaggi

Programming with JXTAProgramming with JXTA

Devono avere home directory

diverse

Page 27: Programming with JXTA

The JxtaServerSocket definisce i seguenti metodi: bind — binds to the pipe within the specified group accept— waits for JxtaSocket connections within the specified

group setSoTimeout — Sets the ServerSocket Timeout

JxtaSocket defines the following methods: create()— toggles reliability getOutputStream ()— returns the output stream for the socket getInputStream() — returns the intput stream for the socket setSoTimeout() — Sets the Socket Timeout

Programming with JXTAProgramming with JXTA

Page 28: Programming with JXTA

import java.io.File;import java.io.InputStream;import java.io.IOException;import java.io.OutputStream;import java.io.FileInputStream;import java.net.Socket;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroupFactory;import net.jxta.exception.PeerGroupException;import net.jxta.document.AdvertisementFactory;import net.jxta.document.MimeMediaType;import net.jxta.socket.JxtaServerSocket;import net.jxta.protocol.PipeAdvertisement;/*** This tutorial illustrates the use JxtaServerSocket It creates a* JxtaServerSocket with a back log of 10. it also blocks indefinitely, until a* connection is established Once a connection is established, it sends* the content of socket.adv and reads data from the remote side.**/

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 29: Programming with JXTA

public class JxtaServerSocketExample {private transient PeerGroup netPeerGroup = null;private transient PipeAdvertisement pipeAdv;private transient JxtaServerSocket serverSocket;

private void sendAndReceiveData(Socket socket) {try { // get the socket output stream

OutputStream out = socket.getOutputStream(); // read a file into a bufferFile file = new File("socket.adv");FileInputStream is = new FileInputStream(file);int size = 4096;byte[] buf = new byte[size]; // send some bytes over the socket (the socket adv is used,

but int read = is.read(buf, 0, size); // that could be anything. It's just a handshake.)

out.write(buf, 0, read);out.flush();System.out.println(read + " bytes sent");InputStream in = socket.getInputStream(); // this call should block until bits are avail.long total = 0;long start = System.currentTimeMillis();while (true) {

read = in.read(buf, 0, size);if (read < 1) { break;}

total += read;} System.out.println("");long elapsed = System.currentTimeMillis() - start;System.out.println("EOT. Received " + total + " bytes in " + elapsed + " ms. Throughput = " +

((total * 8000) / (1024 * elapsed)) + " Kbit/s.");socket.close();System.out.println("Closed connection. Ready for next connection.");

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

}}

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 30: Programming with JXTA

public void run() {System.out.println("starting ServerSocket");while (true) {

try {System.out.println("Calling accept");Socket socket = serverSocket.accept();// set reliableif (socket != null) {

System.out.println("socket created");sendAndReceiveData(socket);

}} catch (Exception e) {

e.printStackTrace();}

}}

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 31: Programming with JXTA

private void startJxta() {try {

System.setProperty("net.jxta.tls.principal", "server");System.setProperty("net.jxta.tls.password", "password");System.setProperty("JXTA_HOME",

System.getProperty("JXTA_HOME","server"));File home = new File(System.getProperty("JXTA_HOME","server"));if (!JxtaSocketExample.configured(home)) { JxtaSocketExample.createConfig(home,

"JxtaServerSocketExample", true);}// create, and Start the default jxta NetPeerGroupnetPeerGroup = PeerGroupFactory.newNetPeerGroup();//JxtaSocketExample.login(netPeerGroup, "server", "password");

} catch (PeerGroupException e) {

// could not instantiate the group, print the stack and exitSystem.out.println("fatal error : group creation failure");e.printStackTrace();System.exit(1);

}}

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 32: Programming with JXTA

public static void main(String args[]) {JxtaServerSocketExample socEx = new JxtaServerSocketExample();socEx.startJxta();System.out.println("Reading in socket.adv");try {

FileInputStream is = new FileInputStream("socket.adv");socEx.pipeAdv = (PipeAdvertisement)AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8,

is);is.close();socEx.serverSocket = new JxtaServerSocket(socEx.netPeerGroup,

socEx.pipeAdv, 10);// block until a connection is availablesocEx.serverSocket.setSoTimeout(0);

} catch (Exception e) {System.out.println("failed to read/parse pipe advertisement");e.printStackTrace();System.exit(-1);

}socEx.run();

}}

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 33: Programming with JXTA

Example pipe advertisement: socket.advAn example pipe advertisement, saved to the file socket.adv, is listed

below:

<!DOCTYPE jxta:PipeAdvertisement><jxta:PipeAdvertisement xmlns:jxta="http://jxta.org">

<Id>urn:jxta:uuid-

59616261646162614E5047205032503393B5C2F6CA7A41FBB0F890173088E79404

</Id><Type>

JxtaUnicast</Type><Name>

socket tutorial</Name>

</jxta:PipeAdvertisement>

Programming with JXTAProgramming with JXTA

Page 34: Programming with JXTA

import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.IOException;import java.io.OutputStream;import net.jxta.credential.AuthenticationCredential;import net.jxta.credential.Credential;import net.jxta.document.AdvertisementFactory;import net.jxta.document.MimeMediaType;import net.jxta.document.StructuredDocument;import net.jxta.exception.PeerGroupException;import net.jxta.impl.membership.pse.StringAuthenticator;import net.jxta.impl.protocol.PlatformConfig;import net.jxta.membership.InteractiveAuthenticator;import net.jxta.membership.MembershipService;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroupFactory;import net.jxta.protocol.PipeAdvertisement;import net.jxta.socket.JxtaSocket;/*** This tutorial illustrates the use JxtaSocket. It attempts to bind a* JxtaSocket to an instance of JxtaServerSocket bound socket.adv. Once a* connection is established, it reads in expected data from the remote* side, and then sends 1824 64K chunks and measures data rate achieved**/

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 35: Programming with JXTA

public class JxtaSocketExample {private transient PeerGroup netPeerGroup = null;private transient PipeAdvertisement pipeAdv;private transient JxtaSocket socket;// number of iterations to send the payloadprivate static int ITERATIONS = 1824;// payload sizeprivate static int payloadSize = 64 * 1024;/*** Starts the NetPeerGroup, and logs in*@exception PeerGroupException if a PeerGroupException occurs*/private void startJxta() throws PeerGroupException {

System.setProperty("net.jxta.tls.principal", "client");System.setProperty("net.jxta.tls.password", "password");System.setProperty("JXTA_HOME",System.getProperty("JXTA_HOME", "client"));File home = new File(System.getProperty("JXTA_HOME", "client"));if (!configured(home)) {

createConfig(home, "JxtaSocketExample", false);}// create, and Start the default jxta NetPeerGroupnetPeerGroup = PeerGroupFactory.newNetPeerGroup();

}

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 36: Programming with JXTA

public void run() throws IOException {int bufsize = 1024;System.out.println("Connecting to the server");socket = new JxtaSocket(netPeerGroup, null, pipeAdv, 30000, true);socket.setOutputStreamBufferSize(65536); // Set buffer size to payload size// The server initiates communication by sending a small data packet and then awaits data from the clientSystem.out.println("Reading in data");InputStream in = socket.getInputStream();byte[] inbuf = new byte[bufsize];int read = in.read(inbuf, 0, bufsize);System.out.println("received " + read + " bytes");// Server is awaiting this data // Send data and time it.System.out.println("Sending back " + payloadSize + " * " + ITERATIONS + " bytes");OutputStream out = socket.getOutputStream();byte[] payload = new byte[payloadSize];long t0 = System.currentTimeMillis();for (int i = 0; i < ITERATIONS; i++) {

out.write(payload, 0, payloadSize);}out.flush();// include close in timing since it may need to flush the tail end of the stream.socket.close();long t1 = System.currentTimeMillis();System.out.println("Completed in :" + (t1 - t0) + " msec");System.out.println("Data Rate :" + ((long) 64 * ITERATIONS * 8000) / (t1 - t0) + " Kbit/sec");

}

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 37: Programming with JXTA

public static void login(PeerGroup group, String principal, String password) {try {

StringAuthenticator auth = null;MembershipService membership = group.getMembershipService();Credential cred = membership.getDefaultCredential();

if (cred == null) {AuthenticationCredential authCred = new AuthenticationCredential(group, "StringAuthentication", null);try { auth = (StringAuthenticator) membership.apply(authCred);} catch (Exception failed) {;}if (auth != null) {

auth.setAuth1_KeyStorePassword(password.toCharArray());auth.setAuth2Identity(group.getPeerID());auth.setAuth3_IdentityPassword(principal.toCharArray());if (auth.isReadyForJoin()) { membership.join(auth); }

}}cred = membership.getDefaultCredential();if (null == cred) {

AuthenticationCredential authCred = new AuthenticationCredential(group, "InteractiveAuthentication", null);

InteractiveAuthenticator iAuth = (InteractiveAuthenticator) membership.apply(authCred);If (iAuth.interact() && iAuth.isReadyForJoin()) { membership.join(iAuth);}

}} catch (Throwable e) {

System.out.flush(); // make sure output buffering doesn't wreck console display.System.err.println("Uncaught Throwable caught by 'main':");e.printStackTrace();System.exit(1); // make note that we abended

}finally {

System.err.flush();System.out.flush();

}}

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 38: Programming with JXTA

/*** returns a resource InputStream*@param resource resource name*@return returns a resource InputStream*@exception IOException if an I/O error occurs*/protected static InputStream getResourceInputStream(String resource) throws

IOException {ClassLoader cl = JxtaSocketExample.class.getClassLoader();return cl.getResourceAsStream(resource);

}

/*** Returns true if the node has been configured, otherwise false**@param home node jxta home directory*@return true if home/PlatformConfig exists*/protected static boolean configured(File home) {

File platformConfig = new File(home, "PlatformConfig");return platformConfig.exists();

}

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 39: Programming with JXTA

protected static void createConfig(File home, String name,boolean server) {try {

String fname = null;if (server) {

fname = "ServerPlatformConfig.master";} else {

fname = "PlatformConfig.master";}InputStream is = getResourceInputStream(fname);home.mkdirs();PlatformConfig platformConfig = (PlatformConfig)AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is);is.close();platformConfig.setName(name);File newConfig = new File(home, "PlatformConfig");OutputStream op = new FileOutputStream(newConfig);StructuredDocument doc = (StructuredDocument)platformConfig.getDocument(MimeMediaType.XMLUTF8);doc.sendToStream(op);op.close();

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

}}

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 40: Programming with JXTA

public static void main(String args[]) {try {

JxtaSocketExample socEx = new JxtaSocketExample();System.out.println("Starting JXTA");socEx.startJxta();System.out.println("reading in socket.adv");FileInputStream is = new FileInputStream("socket.adv");socEx.pipeAdv = (PipeAdvertisement)AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is);is.close();socEx.run(); // run it oncesocEx.run(); // run it again, to exclude any object initialization overhead

} catch (Throwable e) {System.out.println("failed : " + e);e.printStackTrace();System.exit(-1);

}System.exit(0);

}

Programming with JXTAProgramming with JXTAJxtaServerSocketExample

Page 41: Programming with JXTA

DemoDemo

JxtaSocketsJxtaSockets