65
2002 Prentice Hall. All rights reserved. Chapter 28: Peer-to-Peer Applications and JXTA Outline 28.1 Introduction 28.2 Client/Server and Peer-to-Peer Applications 28.3 Centralized vs. Decentralized Network Applications 28.4 Peer Discovery and Searching 28.5 Case Study: Deitel Instant Messenger 28.6 Defining the Service Interface 28.7 Defining the Service implementation 28.8 Registering the Service 28.9 Find Other Peers 28.10 Compiling and Running the Example 28.11 Improving Deitel Instant Messenger 28.12 Deitel Instant Messenger with Multicast Sockets 28.12.1 Registering the Peer 28.12.2 Finding Other Peers 28.13 Introduction to JXTA

Chapter 28: Peer-to-Peer Applications and JXTA

  • Upload
    thuong

  • View
    19

  • Download
    0

Embed Size (px)

DESCRIPTION

Chapter 28: Peer-to-Peer Applications and JXTA. - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

Chapter 28: Peer-to-Peer Applications and JXTA

Outline28.1 Introduction28.2 Client/Server and Peer-to-Peer Applications28.3 Centralized vs. Decentralized Network Applications28.4 Peer Discovery and Searching28.5 Case Study: Deitel Instant Messenger28.6 Defining the Service Interface28.7 Defining the Service implementation28.8 Registering the Service28.9 Find Other Peers28.10 Compiling and Running the Example28.11 Improving Deitel Instant Messenger28.12 Deitel Instant Messenger with Multicast Sockets

28.12.1 Registering the Peer28.12.2 Finding Other Peers

28.13 Introduction to JXTA

Page 2: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.1 Introduction

• Peer-to-peer (P2P) application– Each node performs both client and server functions

– Distribution of processing responsibilities

Page 3: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.2 Client/Server and Peer-to-Peer Applications

• Client/Server application– e.g., Yahoo! search engine

– Server offers common stores of programs and data

– Client access the data provided by servers

• Peer-to-peer (P2P) application– All computers act as both client and server

Page 4: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.2 Client/Server and Peer-to-Peer Applications (cont.)

Distributed Applications Description Gnutella A P2P technology that does not use any central servers. There is no authentication, and peers

search for files via a distributed-search mechanism.

KaZaA A file-sharing application that is a hybrid between Gnutella and centralized applications. A

central server authenticates all users. Certain peers serve as search hubs, which catalog the files of peers connected to them. Searches are distributed to each search hub, which then respond with results that allow direct connections for file transfers.

Instant Messengers Peer-to-peer applications that enable users to send short text messages and files to one another. Most instant messengers use central servers that authenticate all users and route messages between peers.

Telephone System A peer-to-peer application that enables users to conduct voice conversations remotely.

Fig. 28.1 Common P2P applications.

Page 5: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.3 Centralized vs. Decentralized Network Applications

• Centralized server– Weakness: dependency on central server

• If central server fails, so does the entire application

• Decentralized server– True P2P application

– No dependency on single node• If one node fails, the application can exist

Page 6: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.4 Peer Discovery and Searching

• Peer discovery– Finding peers in P2P application

– Decentralizing an application often slows peer discovery

• Distributed searching– Peer sends search criteria to several nearby peers

– Searching performed by several systems

Page 7: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.5 Case Study: Deitel Instant Messenger

• Deitel Instant Messenger– P2P application

– Uses Jini to bootstrap (register) users onto the P2P network

Page 8: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.5 Case Study: Deitel Instant Messenger (cont.)

Fig. 28.2 Sample windows of Deitel Instant Messenger.

Page 9: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.3 Interface IMService specifies how service proxy interacts with the service.

Lines 16-17

1 // IMService.java2 // IMService interface defines the methods3 // through which the service proxy4 // communicates with the service.5 package com.deitel.advjhtp1.jini.IM.service;6 7 // Java core packages8 import java.rmi.*;9 10 // Deitel packages11 import com.deitel.advjhtp1.jini.IM.IMPeer;12 13 public interface IMService extends Remote {14 15 // return RMI reference to a remote IMPeer 16 public IMPeer connect( IMPeer sender ) 17 throws RemoteException;18 }

Enables users to send a remote reference to an IMPeer

Page 10: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.4 Interface IMPeer specifies interaction between peers.

Line 9

Lines 12-13

1 // IMPeer.java2 // Interface that all Peer to Peer apps must implement3 package com.deitel.advjhtp1.jini.IM;4 5 //java core packages6 import java.rmi.*;7 import java.util.*;8 9 public interface IMPeer extends Remote 10 {11 // posts Message to peer 12 public void sendMessage( Message message ) 13 throws RemoteException;14 15 // information methods16 public String getName() throws RemoteException;17 }

Clients send messages to peers by calling sendMessage

Specifies the interface for communicating between peers

Page 11: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.5 Class Message defines an object for sending and receiving messages between peers (part 1).

Line 9

Lines 16-21

1 // Message.java2 // Message represents an object that can be sent to an IMPeer;3 // contains the sender and content of the message.4 package com.deitel.advjhtp1.jini.IM;5 6 // Java core package7 import java.io.Serializable;8 9 public class Message implements Serializable10 {11 private static final long SerialVersionUID = 20010808L;12 private String from;13 private String content;14 15 // Message constructor16 public Message( String messageSenderName, 17 String messageContent )18 {19 from = messageSenderName;20 content = messageContent;21 } 22 23 // get String representation24 public String toString()25 {26 return from + ": " + content + "\n";27 }28 29 // get Message sender's name30 public String getSenderName()31 {32 return from;33 }

Messages must be serialized for delivery over RMI

Message constructor takes as arguments the sender’s name and message content

Page 12: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.5 Class Message defines an object for sending and receiving messages between peers (part 2).

34 35 // get Message content36 public String getContent()37 {38 return content;39 }40 }

Page 13: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.7 Defining the Service Implementation

• Define service implementation– IMServiceImpl

• Implements interface IMService• Extends UnicastRemoteObject

Page 14: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.6 IMServiceImpl service implementation for our case study(part 1).

Line 18

Lines 28-31

1 // IMServiceImpl.java2 // IMServiceImpl implements IMService interface3 // is service side of IM application4 package com.deitel.advjhtp1.jini.IM.service;5 6 // Java core packages7 import java.io.*;8 import java.rmi.server.UnicastRemoteObject;9 import java.rmi.RemoteException;10 import java.util.StringTokenizer;11 12 // Deitel packages13 import com.deitel.advjhtp1.jini.IM.IMPeer;14 import com.deitel.advjhtp1.jini.IM.IMPeerImpl;15 import com.deitel.advjhtp1.jini.IM.Message;16 import com.deitel.advjhtp1.jini.IM.client.IMPeerListener;17 18 public class IMServiceImpl extends UnicastRemoteObject 19 implements IMService, Serializable {20 21 private static final long SerialVersionUID = 20010808L;22 private String userName = "Anonymous";23 24 // IMService no-argument constructor25 public IMServiceImpl() throws RemoteException{}26 27 // IMService constructor takes userName28 public IMServiceImpl( String name ) throws RemoteException29 {30 userName = name;31 }32

Define the service implementation

Second constructor takes as a String argument the

user’s name, which appears in the PeerList window

Page 15: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.6 IMServiceImpl service implementation for our case study(part 2).

Line 40

Line 51

Line 54

33 // sets service s userName34 public void setUserName( String name ) 35 {36 userName = name;37 }38 39 // return RMI reference to an IMPeer on the receiver side40 public IMPeer connect( IMPeer sender ) 41 throws RemoteException42 {43 // Make a GUI and IMPeerImpl to be sent to remote peer44 IMPeerListener listener = 45 new IMPeerListener( userName );46 47 IMPeerImpl me = new IMPeerImpl( userName );48 me.addListener( listener );49 50 // add remote peer to my GUI51 listener.addPeer( sender );52 53 //send my IMPeerImpl to him54 return me;55 56 } // end method connect57 }

First peer sends reference of itself to second peer by

invoking IMService method connect

Second Peer stores first peer’s reference for use

when conversation starts

Second peer returns reference of itself to first peer

Page 16: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.7 IMPeerListener is the GUI that starts peer communication (part 1).

Line 20

1 // IMPeerListener.java2 // IMPeerListener extends JFrame and provides GUI for 3 // conversations with other peers 4 package com.deitel.advjhtp1.jini.IM.client;5 6 // Java core packages7 import java.awt.*;8 import java.awt.event.*;9 import java.rmi.RemoteException;10 11 // Java extension packages12 import javax.swing.*;13 import javax.swing.text.*;14 import javax.swing.border.*;15 16 // Deitel Packages17 import com.deitel.advjhtp1.jini.IM.IMPeer;18 import com.deitel.advjhtp1.jini.IM.Message;19 20 public class IMPeerListener extends JFrame {21 22 // JTextAreas for displaying and inputting messages23 private JTextArea messageArea;24 private JTextArea inputArea;25 26 // Actions for sending messages, etc.27 private Action sendAction;28 29 // userName to add to outgoing messages30 private String userName = "";31 32 // IMPeer to send messages to peer33 private IMPeer remotePeer;34

GUI for starting peer communication

Page 17: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.7 IMPeerListener is the GUI that starts peer communication (part 2).

35 // constructor 36 public IMPeerListener( String name )37 {38 super( "Conversation Window" );39 40 // set user name41 userName = name;42 43 // init sendAction44 sendAction = new SendAction();45 46 // create JTextArea for displaying messages47 messageArea = new JTextArea( 15, 15 );48 49 // disable editing and wrap words at end of line50 messageArea.setEditable( false );51 messageArea.setLineWrap( true );52 messageArea.setWrapStyleWord( true );53 54 JPanel panel = new JPanel();55 panel.setLayout( new BorderLayout( 5, 5 ) );56 panel.add( new JScrollPane( messageArea ), 57 BorderLayout.CENTER );58 59 // create JTextArea for entering new messages60 inputArea = new JTextArea( 4, 12 ); 61 inputArea.setLineWrap( true );62 inputArea.setWrapStyleWord( true );63 64 // map Enter key in inputArea area to sendAction65 Keymap keyMap = inputArea.getKeymap();66 KeyStroke enterKey = KeyStroke.getKeyStroke(67 KeyEvent.VK_ENTER, 0 );68 keyMap.addActionForKeyStroke( enterKey, sendAction );69

Page 18: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.7 IMPeerListener is the GUI that starts peer communication (part 3).

70 // lay out inputArea and sendAction JButton in Box71 Box box = Box.createVerticalBox();72 box.add( new JScrollPane( inputArea ) );73 box.add( new JButton( sendAction ) );74 75 panel.add( box, BorderLayout.SOUTH );76 77 // lay out components78 Container container = getContentPane();79 container.add( panel, BorderLayout.CENTER );80 81 setSize( 200, 400 );82 setVisible( true );83 }84 85 // Action for sending messages86 private class SendAction extends AbstractAction {87 88 // configure SendAction89 public SendAction()90 {91 putValue( Action.NAME, "Send" );92 putValue( Action.SHORT_DESCRIPTION, 93 "Send Message" );94 putValue( Action.LONG_DESCRIPTION, 95 "Send an Instant Message" );96 }97 98 // send message and clear inputArea99 public void actionPerformed( ActionEvent event )100 {101 // send message to server102 try {103 Message message = new Message( userName, 104 inputArea.getText() );

Page 19: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.7 IMPeerListener is the GUI that starts peer communication (part 4).

Line 107

105 106 // use RMI reference to send a Message107 remotePeer.sendMessage( message );108 109 // clear inputArea110 inputArea.setText( "" );111 displayMessage( message );112 }113 114 // catch error sending message115 catch( RemoteException remoteException ) {116 JOptionPane.showMessageDialog( null,117 "Unable to send message." );118 119 remoteException.printStackTrace();120 } 121 } // end method actionPerformed122 123 } // end sendAction inner class124 125 public void displayMessage( Message message )126 {127 // displayMessage uses SwingUntilities.invokeLater 128 // to ensure thread-safe access to messageArea129 SwingUtilities.invokeLater(130 new MessageDisplayer( 131 message.getSenderName(), message.getContent() ) );132 }133 134 // MessageDisplayer displays a new message by appending135 // the message to the messageArea JTextArea. This Runnable136 // object should be executed only on the event-dispatch137 // thread, as it modifies a live Swing component.138 private class MessageDisplayer implements Runnable {139

When user presses JButton, call method sendMessage of remote peer

Page 20: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.7 IMPeerListener is the GUI that starts peer communication (part 5).

Lines 167-173

140 private String fromUser;141 private String messageBody;142 143 // MessageDisplayer constructor144 public MessageDisplayer( String from, String body )145 {146 fromUser = from;147 messageBody = body;148 }149 150 // display new message in messageArea151 public void run() 152 {153 // append new message154 messageArea.append( "\n" + fromUser + "> " + 155 messageBody ); 156 157 // move caret to end of messageArea to ensure new 158 // message is visible on screen159 messageArea.setCaretPosition( 160 messageArea.getText().length() ); 161 } 162 163 } // end MessageDisplayer inner class 164 165 // addPeer takes IMPeer as arg166 // associates IMPeer with sendAction to send messages167 public void addPeer( IMPeer peer ) throws RemoteException168 {169 remotePeer = peer;170 171 // change title of window to name of peer172 setTitle( remotePeer.getName() );173 } 174 }

Stores reference to remote IMPeer and set title of

conversation window to the name of remote IMPeer

Page 21: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.8 Class IMPeerImpl is the IMPeer implementation (part 1).

Line 17

1 // IMPeerImpl.java2 // Implements the IMPeer interface3 package com.deitel.advjhtp1.jini.IM;4 5 // Java core packages6 import java.io.*;7 import java.net.*;8 import java.rmi.*;9 import java.rmi.server.*;10 import java.util.*;11 12 // Deitel Packages13 import com.deitel.advjhtp1.jini.IM.Message;14 import com.deitel.advjhtp1.jini.IM.client.IMPeerListener;15 16 17 public class IMPeerImpl extends UnicastRemoteObject 18 implements IMPeer {19 20 private String name;21 private IMPeerListener output;22 23 // No argument constructor24 public IMPeerImpl() throws RemoteException25 {26 super();27 name = "anonymous";28 }29 // constructor takes userName30 public IMPeerImpl( String myName ) throws RemoteException31 {32 name = myName;33 }34

Define the peer implementation

Page 22: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.8 Class IMPeerImpl is the IMPeer implementation (part 2).

Lines 35-38

Lines 41-45

35 public void addListener( IMPeerListener listener )36 {37 output = listener;38 }39 40 // send message to this peer41 public void sendMessage( Message message ) 42 throws RemoteException43 {44 output.displayMessage( message );45 }46 47 // accessor for name48 public String getName() throws RemoteException49 {50 return name;51 } 52 }

Override method sendMessage to send message to peer

Add an object of type IMPeer-Listener that will display the

IMPeerImpl’s actions

Page 23: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.8 Registering the Service

• Register (bootstrap) service with peer group

Page 24: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.9 Class IMServiceManager registers IMServiceImpl with lookup services(part 1).

Line 33

1 // IMServiceManager.java2 // IMServiceManager uses JoinManager to find Lookup services,3 // registers the IMService with the Lookup services,4 // manages lease renewal5 package com.deitel.advjhtp1.jini.IM;6 7 // Java core packages8 import java.rmi.RMISecurityManager;9 import java.rmi.RemoteException;10 import java.io.IOException;11 12 // Jini core packages13 import net.jini.core.lookup.ServiceID;14 import net.jini.core.entry.Entry;15 16 // Jini extension packages17 import net.jini.lookup.entry.Name;18 import net.jini.lease.LeaseRenewalManager;19 import net.jini.lookup.JoinManager;20 import net.jini.discovery.LookupDiscoveryManager;21 import net.jini.lookup.ServiceIDListener;22 23 // Deitel packages24 import com.deitel.advjhtp1.jini.IM.service.*;25 26 public class IMServiceManager implements ServiceIDListener {27 28 JoinManager manager;29 LookupDiscoveryManager lookupManager;30 String serviceName;31 32 // constructor takes name of the service33 public IMServiceManager( String screenName )34 {35 System.setSecurityManager( new RMISecurityManager() );

Constructor takes a String that specifies the Name Entry for the service

Page 25: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.9 Class IMServiceManager registers IMServiceImpl with lookup services(part 2).

Line 56

36 37 // sets the serviceName of this service38 serviceName = screenName;39 40 // use JoinManager to register SeminarInfo service 41 // and manage lease42 try {43 44 // create LookupDiscoveryManager for discovering45 // lookup services46 lookupManager = 47 new LookupDiscoveryManager( new String[] { "" }, 48 null, null );49 50 // create and set Entry name for service51 // name used from constructor52 Entry[] entries = new Entry[ 1 ];53 entries[ 0 ] = new Name( serviceName ); 54 55 // create JoinManager56 manager = new JoinManager( createProxy(),57 entries, this, lookupManager, 58 new LeaseRenewalManager() );59 }60 61 // handle exception creating JoinManager62 catch ( IOException exception ) {63 exception.printStackTrace();64 }65 } // end SeminarInfoJoinService constructor66 67 // return the LookupDiscoveryManager created by JoinManager68 public LookupDiscoveryManager getDiscoveryManager()69 {70 return lookupManager;

Use Jini’s JoinManager class to register the service

with all known lookup services

Page 26: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.9 Class IMServiceManager registers IMServiceImpl with lookup services(part 3).

71 }72 73 // create service proxy74 private IMService createProxy()75 {76 // get SeminarProxy for SeminarInfo service77 try {78 return( new IMServiceImpl( serviceName ) );79 }80 81 // handle exception creating SeminarProxy82 catch ( RemoteException exception ) {83 exception.printStackTrace();84 }85 86 return null;87 88 } // end method createProxy89 90 // receive notification of ServiceID assignment91 public void serviceIDNotify( ServiceID serviceID )92 {93 System.err.println( "Service ID: " + serviceID );94 }95 96 // informs all lookup services that service is ending97 public void logout()98 {99 manager.terminate();100 }101 }

Page 27: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.9 Find Other Peers

• Create GUI enabling user to find other peers

Page 28: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.10 Class PeerList is the GUI for finding peers (part 1).

Lines 33-34

1 // PeerList.java2 // Initializes ServiceManager, starts service discovery3 // and lists all IM services in a window4 package com.deitel.advjhtp1.jini.IM;5 6 // Java core packages7 import java.awt.*;8 import java.awt.event.*;9 import java.net.MalformedURLException;10 import java.util.*;11 import java.util.List;12 import java.io.IOException;13 import java.rmi.*;14 15 // Java extension packages16 import javax.swing.*;17 import javax.swing.event.*;18 19 // Jini core packages20 import net.jini.core.lookup.ServiceItem;21 import net.jini.core.lookup.ServiceTemplate;22 import net.jini.lookup.*;23 import net.jini.discovery.LookupDiscoveryManager;24 import net.jini.lease.LeaseRenewalManager;25 import net.jini.lookup.entry.Name;26 import net.jini.core.entry.Entry;27 import net.jini.core.discovery.LookupLocator;28 29 // Deitel Packages30 import com.deitel.advjhtp1.jini.IM.service.IMService;31 import com.deitel.advjhtp1.jini.IM.client.IMPeerListener;32 33 public class PeerList extends JFrame 34 implements ServiceDiscoveryListener {35

PeerList is the main window of the Deitel Instant Messenger

Page 29: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.10 Class PeerList is the GUI for finding peers (part 2).

Line 53

Lines 57-65

36 private DefaultListModel peers;37 private JList peerList;38 private List serviceItems;39 private ServiceDiscoveryManager serviceDiscoveryManager;40 private LookupCache cache;41 private IMServiceManager myManager;42 private LookupDiscoveryManager lookupDiscoveryManager;43 44 // initialize userName to anonymous45 private String userName = "anonymous";46 47 // method called when ServiceDiscoveryManager finds 48 // IM service adds service proxy to serviceItems49 // adds Service name to ListModel for JList50 public void serviceAdded( ServiceDiscoveryEvent event )51 {52 // get added serviceItem53 ServiceItem item = event.getPostEventServiceItem(); 54 Entry attributes[] = item.attributeSets;55 56 // iterates through attributes to find name57 for( int i = 0; i < attributes.length; i++ )58 59 if ( attributes[ i ] instanceof Name ) {60 System.out.println( "Added: " + item );61 serviceItems.add( item.service ); 62 peers.addElement(63 ( ( Name )attributes[ i ] ).name );64 break;65 } 66 } // end method serviceAdded67 68 // empty method ignores seviceChanged event69 public void serviceChanged( ServiceDiscoveryEvent event )70 {}

Obtain a ServiceItem that represents the added service

Add service proxy to List and add Name to Default-ListModel if Name entry

Page 30: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.10 Class PeerList is the GUI for finding peers (part 3).

71 72 // removes services from PeerList GUI and data structure73 // when serviceRemoved event occurs74 public void serviceRemoved( ServiceDiscoveryEvent event )75 {76 // getPreEvent because item has been removed77 // getPostEvent would return null78 ServiceItem item = event.getPreEventServiceItem();79 Entry attributes[ ] = item.attributeSets;80 81 // debug82 System.out.println( "Remove Event!" );83 84 // remove from arraylist and DefaultListModel85 int index = serviceItems.indexOf( item.service );86 87 // print name of person removed88 if ( index >= 0 )89 {90 System.out.println( "Removing from List:" + 91 serviceItems.remove( index ));92 93 System.out.println( "Removing from DefList" + 94 peers.elementAt( index ) );95 96 peers.removeElementAt( index );97 }98 } // end method ServiceRemoved99 100 // constructor101 public PeerList()102 {103 super( "Peer List" );104 105 System.setSecurityManager( new RMISecurityManager() );

Page 31: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.10 Class PeerList is the GUI for finding peers (part 4).

Lines 135-138

106 107 // get desired userName108 userName = JOptionPane.showInputDialog( 109 PeerList.this, "Please enter your name: " );110 111 // change title of window112 setTitle( userName + "'s Peer List Window" );113 114 // Init Lists115 serviceItems = new ArrayList();116 117 Container container = getContentPane();118 peers = new DefaultListModel();119 120 // init components121 peerList = new JList( peers );122 peerList.setVisibleRowCount( 5 );123 JButton connectButton = new JButton( "Connect" );124 125 // do not allow multiple selections126 peerList.setSelectionMode(127 ListSelectionModel.SINGLE_SELECTION );128 129 // set up event handler for connectButton130 connectButton.addActionListener(131 new ActionListener() {132 133 public void actionPerformed( ActionEvent event )134 {135 int itemIndex = peerList.getSelectedIndex();136 137 Object selectedService = 138 serviceItems.get( itemIndex );139 IMService peerProxy = 140 ( IMService )selectedService;

Use index of selected JList item to retrieve IMService proxy

Page 32: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.10 Class PeerList is the GUI for finding peers (part 5).

Lines 147-151

Lines 154-155

141 142 // send info to remote peer143 // get RMI reference144 try {145 146 // set up gui and my peerImpl147 IMPeerListener gui = 148 new IMPeerListener( userName );149 IMPeerImpl me = 150 new IMPeerImpl( userName );151 me.addListener( gui );152 153 // Connect myGui to remote IMPeer object154 IMPeer myPeer = peerProxy.connect( me );155 gui.addPeer( myPeer );156 }157 158 // connecting may cause RemoteException159 catch( RemoteException re ) {160 JOptionPane.showMessageDialog161 ( null, "Couldn't Connect" );162 re.printStackTrace();163 }164 } 165 }166 ); // end connectButton actionListener167 168 // set up File menu169 JMenu fileMenu = new JMenu( "File" );170 fileMenu.setMnemonic( 'F' );171

Create IMPeerListener for IMPeerImpl

IMPeerImpl will post all messages sent by remote peer

to IMPeerListener

Page 33: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.10 Class PeerList is the GUI for finding peers (part 6).

Lines 189-223

172 // about Item173 JMenuItem aboutItem = new JMenuItem( "About..." );174 aboutItem.setMnemonic( 'A' );175 aboutItem.addActionListener( 176 new ActionListener() {177 public void actionPerformed( ActionEvent event )178 {179 JOptionPane.showMessageDialog( PeerList.this, 180 "Deitel Instant Messenger" ,181 "About", JOptionPane.PLAIN_MESSAGE );182 }183 }184 );185 186 fileMenu.add( aboutItem );187 188 // AddLocator item189 JMenuItem federateItem = 190 new JMenuItem( "Add Locators" );191 federateItem.setMnemonic( 'L' );192 federateItem.addActionListener(193 194 new ActionListener() {195 public void actionPerformed( ActionEvent event )196 { 197 // get LookupService url to be added198 String locator = 199 JOptionPane.showInputDialog( 200 PeerList.this, 201 "Please enter locator in this" +202 "form: jini://host:port/" );203 204 try {205 LookupLocator newLocator = 206 new LookupLocator( locator );

Create dialog box to prompt user for Jini-lookup-service URL

Page 34: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.10 Class PeerList is the GUI for finding peers (part 7).

Line 212

207 208 // make one element LookupLocator array209 LookupLocator[] locators = { newLocator };210 211 // because addLocators takes array212 lookupDiscoveryManager.addLocators( locators );213 }214 215 catch( MalformedURLException urlException) {216 217 JOptionPane.showMessageDialog( 218 PeerList.this, "invalid url" );219 }220 }221 }222 );223 fileMenu.add( federateItem );224 225 // set up JMenuBar and attach File menu226 JMenuBar menuBar = new JMenuBar();227 menuBar.add ( fileMenu );228 setJMenuBar( menuBar );229 230 // handow window closing event231 addWindowListener(232 new WindowAdapter(){233 public void windowClosing( WindowEvent w )234 {235 System.out.println( "CLOSING WINDOW" );236 237 // disconnects from lookup services238 myManager.logout();239 System.exit( 0 );240 }241 }

Client registers with newly added lookup service;

PeerList window lists all other peers registered with new lookup service

Page 35: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.10 Class PeerList is the GUI for finding peers (part 8).

Line 263

242 ); 243 244 // lay out GUI components 245 peerList.setFixedCellWidth( 100 );246 JPanel inputPanel = new JPanel();247 inputPanel.add( connectButton );248 249 container.add( new JScrollPane( peerList ) ,250 BorderLayout.NORTH );251 container.add( inputPanel, BorderLayout.SOUTH );252 253 setSize( 100, 170 );254 setVisible( true );255 256 // peer list displays only other IMServices257 Class[] types = new Class[] { IMService.class };258 ServiceTemplate IMTemplate = 259 new ServiceTemplate( null, types, null );260 261 // Initialize IMServiceManager, ServiceDiscoveryManager262 try {263 myManager = new IMServiceManager( userName ); 264 265 // store LookupDiscoveryManager 266 // generated by IMServiceManager267 lookupDiscoveryManager = myManager.getDiscoveryManager();268 269 // ServiceDiscoveryManager uses lookupDiscoveryManager270 serviceDiscoveryManager = 271 new ServiceDiscoveryManager( lookupDiscoveryManager,272 null );273 274 // create a LookupCache275 cache = serviceDiscoveryManager.createLookupCache(276 IMTemplate, null, this );

Create the IMServiceManager, using userName to name the peer

Page 36: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.10 Class PeerList is the GUI for finding peers (part 9).

277 }278 279 // catch all exceptions and inform user of problem280 catch ( Exception managerException) {281 JOptionPane.showMessageDialog( null, 282 "Error initializing IMServiceManger" +283 "or ServiceDisoveryManager" );284 managerException.printStackTrace();285 }286 }287 288 public static void main( String args[] )289 {290 new PeerList();291 }292 }

Page 37: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.10 Compiling and Running the Example

• 1. Compile classes• 2. Compile remote classes via rmic• 3. Start rmid• 4. Start HTTP server• 5. Start lookup service

Page 38: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.11 Improving Deitel Instant Messenger

• Limitations– Not secure

– Not scalable

• Solutions– Filters

• limit the number of service proxies that ServiceDiscoveryManager downloads

– Distributed searches• Facilitate locating peers

Page 39: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.12 Deitel Instant Messenger with Multicast Sockets

• True P2P application– Each node must run lookup service

• Requires significant amounts of memory and processor time

– Solution:• Use Multicast sockets

– Advertise and find peers in network

Page 40: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.12.1 Registering the Peer

• Jini implementation– provided mechanism to register and find peers

– We must implement this mechanism via multicast sockets

Page 41: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.11 MulticastSendingThread broadcasts DatagramPackets (part 1).

Line 17

1 // MulticastSendingThread.java2 // Sends a multicast periodically containing a remote reference 3 // to the IMServiceImpl object4 package com.deitel.advjhtp1.p2p;5 6 // Java core packages7 import java.net.MulticastSocket;8 import java.net.*;9 import java.rmi.*;10 import java.rmi.registry.*;11 import java.io.*;12 13 // Deitel core packages14 import com.deitel.advjhtp1.jini.IM.service.IMServiceImpl;15 import com.deitel.advjhtp1.jini.IM.service.IMService;16 17 public class MulticastSendingThread extends Thread 18 implements IMConstants {19 20 // InetAddress of group for messages21 private InetAddress multicastNetAddress;22 23 // MulticastSocket for multicasting messages24 private MulticastSocket multicastSocket;25 26 // Datagram packet to be reused27 private DatagramPacket multicastPacket;28 29 // stub of local peer30 private IMService peerStub; 31 32 // flag for terminating MulticastSendingThread33 private boolean keepSending = true;34 35 private String userName;

MulticastSendingThread multicasts a peer’s presence

Page 42: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.11 MulticastSendingThread broadcasts DatagramPackets (part 2).

Lines 47-48

Line 49

Lines 59-60

36 37 // MulticastSendingThread constructor38 public MulticastSendingThread( String myName )39 {40 // invoke superclass constructor to name Thread41 super( "MulticastSendingThread" );42 43 userName = myName;44 45 // create a registry on default port 109946 try {47 Registry registry = 48 LocateRegistry.createRegistry( 1099 );49 peerStub = new IMServiceImpl( userName );50 registry.rebind( BINDING_NAME, peerStub );51 }52 catch ( RemoteException remoteException ) {53 remoteException.printStackTrace();54 }55 56 try {57 58 // create MulticastSocket for sending messages59 multicastSocket = 60 new MulticastSocket ( MULTICAST_SENDING_PORT );61 62 // set TTL for Multicast Socket63 multicastSocket.setTimeToLive( MULTICAST_TTL );64 65 // use InetAddress reserved for multicast group66 multicastNetAddress = InetAddress.getByName(67 MULTICAST_ADDRESS ); 68 69 // create greeting packet70 String greeting = new String( HELLO_HEADER + userName );

Call createRegistry to instantiate an RMI registry on port 1099

Rebind IMServiceImpl to RMI registry

Instantiate MulticastSocket for sending messages to peers

Page 43: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.11 MulticastSendingThread broadcasts DatagramPackets (part 3).

Lines 72-74

Lines 100

71 72 multicastPacket = new DatagramPacket(73 greeting.getBytes(), greeting.getBytes().length, 74 multicastNetAddress, MULTICAST_LISTENING_PORT );75 }76 77 // MULTICAST_ADDRESS IS UNKNOWN HOST78 catch ( java.net.UnknownHostException unknownHostException )79 {80 System.err.println( "MULTICAST_ADDRESS is unknown" );81 unknownHostException.printStackTrace();82 }83 84 // any other exception85 catch ( Exception exception )86 {87 exception.printStackTrace();88 }89 }90 91 // deliver greeting message to peers92 public void run()93 {94 while ( keepSending ) {95 96 // deliver greeting97 try {98 99 // send greeting packet100 multicastSocket.send( multicastPacket );101 102 Thread.sleep( MULTICAST_INTERVAL );103 }104

Create message packet containing peer’s name

Send message via MulticastSocket

Page 44: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.11 MulticastSendingThread broadcasts DatagramPackets (part 4).

Lines 123-130

105 // handle exception delivering message106 catch ( IOException ioException ) {107 ioException.printStackTrace();108 continue;109 }110 catch ( InterruptedException interruptedException ) {111 interruptedException.printStackTrace();112 }113 114 } // end while115 116 multicastSocket.close();117 118 } // end method run119 120 // send goodbye message121 public void logout()122 { 123 String goodbye = new String( GOODBYE_HEADER + userName );124 System.out.println( goodbye );125 multicastPacket = new DatagramPacket(126 goodbye.getBytes(), goodbye.getBytes().length, 127 multicastNetAddress, MULTICAST_LISTENING_PORT );128 129 try {130 multicastSocket.send( multicastPacket );131 132 Naming.unbind( BINDING_NAME );133 }134 135 // error multicasting136 catch ( IOException ioException ) {137 System.err.println( "Could not Say Goodbye“ );138 ioException.printStackTrace();139 }

Send message indicating that the peer is leaving network

Page 45: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.11 MulticastSendingThread broadcasts DatagramPackets (part 5).

140 141 // unbinding may cause many possible exceptions142 catch ( Exception unbindingException ) {143 unbindingException.printStackTrace();144 }145 146 keepSending = false;147 148 } 149 }

Page 46: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.12 Interface IMConstants defines Deitel-Instant-Messenger constants.

Lines 5-34

1 // IMConstants.java2 // contains constants used by IM application3 package com.deitel.advjhtp1.p2p;4 5 public interface IMConstants {6 7 public static final String MULTICAST_ADDRESS = "228.5.6.10";8 9 public static final int MULTICAST_TTL = 30;10 11 // port on local machine for broadcasting 12 public static final int MULTICAST_SENDING_PORT = 6800;13 14 // port on local machine for receiving broadcasts15 public static final int MULTICAST_RECEIVING_PORT = 6789;16 17 // port on multicast ip address to send packets 18 public static final int MULTICAST_LISTENING_PORT = 6789; 19 20 public static final String HELLO_HEADER = "HELLOIM: ";21 22 public static final String GOODBYE_HEADER = "GOODBYE: ";23 24 // time in milliseconds to wait between each multicast25 public static final int MULTICAST_INTERVAL = 10000; 26 27 // how many MUTLICAST_INTERVALS before LEASE EXPIRATION28 public static final int PEER_TTL = 5;29 30 public static final int MESSAGE_SIZE = 256; 31 32 public static String BINDING_NAME = "IMSERVICE";33 34 }

Definition of several constants used in the

multicast-socket version of Deitel

Instant Messenger

Page 47: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.12.2 Finding Other Peers

• Jini implementation– Listed new peers

– Removed peers that left network

Page 48: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.13 Class Multicast-ReceivingThread uses threads to add and remove peers (part 1).

Line 14

1 // MulticastReceivingThread.java2 // Receive and process multicasts from multicast group3 package com.deitel.advjhtp1.p2p;4 5 // Java core packages6 import java.net.MulticastSocket;7 import java.net.*;8 import java.io.*;9 import java.util.*;10 11 // Deitel packages12 import com.deitel.advjhtp1.p2p.PeerDiscoveryListener;13 14 public class MulticastReceivingThread extends Thread 15 implements IMConstants {16 17 // HashMap containing peer names and time to live18 // used to implement leasing19 private HashMap peerTTLMap;20 21 // LeasingThread reference22 private LeasingThread leasingThread;23 24 // object that will respond to peer added or removed events25 private PeerDiscoveryListener peerDiscoveryListener;26 27 // MulticastSocket for receiving broadcast messages28 private MulticastSocket multicastSocket;29 30 // InetAddress of group for messages31 private InetAddress multicastNetAddress;32 33 // flag for terminating MulticastReceivingThread34 private boolean keepListening = true;35

MulticastReceiving-Thread listens for

DatagramPackets that contain notifications of peers joining and leaving network

Page 49: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.13 Class Multicast-ReceivingThread uses threads to add and remove peers (part 2).

Lines 48-49

Lines 69-70

36 // MulticastReceivingThread constructor37 public MulticastReceivingThread( String userName, 38 PeerDiscoveryListener peerEventHandler )39 {40 // invoke superclass constructor to name Thread41 super( "MulticastReceivingThread" );42 43 // set peerDiscoveryListener44 peerDiscoveryListener = peerEventHandler;45 46 // connect MulticastSocket to multicast address and port47 try {48 multicastSocket = 49 new MulticastSocket( MULTICAST_RECEIVING_PORT );50 51 multicastNetAddress = 52 InetAddress.getByName( MULTICAST_ADDRESS );53 54 // join multicast group to receive messages55 multicastSocket.joinGroup( multicastNetAddress );56 57 // set 5 second time-out when waiting for new packets58 multicastSocket.setSoTimeout( 5000 );59 }60 61 // handle exception connecting to multicast address62 catch( IOException ioException ) {63 ioException.printStackTrace();64 }65 66 peerTTLMap = new HashMap();67 68 // create Leasing thread which decrements TTL of peers69 leasingThread = new LeasingThread();70 leasingThread.setDaemon( true );

Instantiate MulticastSocket to join multicast group

Start LeasingThread as deamon thread

Page 50: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.13 Class Multicast-ReceivingThread uses threads to add and remove peers (part 3).

Lines 84-89

71 leasingThread.start(); 72 73 } // end MulticastReceivingThread constructor74 75 // listen for messages from multicast group76 public void run()77 {78 while( keepListening ) {79 80 // create buffer for incoming message81 byte[] buffer = new byte[ MESSAGE_SIZE ];82 83 // create DatagramPacket for incoming message84 DatagramPacket packet = new DatagramPacket( buffer, 85 MESSAGE_SIZE );86 87 // receive new DatagramPacket (blocking call)88 try {89 multicastSocket.receive( packet );90 }91 92 // handle exception when receive times out93 catch ( InterruptedIOException interruptedIOException ) {94 95 // continue to next iteration to keep listening96 continue;97 }98 99 // handle exception reading packet from multicast group100 catch ( IOException ioException ) {101 ioException.printStackTrace();102 break;103 }104

Receive DatagramPacket from MulticastSocket

Page 51: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.13 Class Multicast-ReceivingThread uses threads to add and remove peers (part 4).

Lines 105-106

Lines 118-127

Lines 135-136

105 // put message data into String106 String message = new String( packet.getData(), 107 packet.getOffset(), packet.getLength() );108 109 // ensure non-null message110 if ( message != null ) {111 112 // trim extra whitespace from end of message113 message = message.trim();114 115 System.out.println( message );116 117 // decide if goodbye or hello118 if ( message.startsWith( HELLO_HEADER ) ) {119 processHello( 120 message.substring( HELLO_HEADER.length() ),121 packet.getAddress().getHostAddress()122 );123 }124 125 else if ( message.startsWith( GOODBYE_HEADER ) )126 processGoodbye( message.substring( 127 GOODBYE_HEADER.length() ) );128 129 } // end if130 131 } // end while132 133 // leave multicast group and close MulticastSocket134 try {135 multicastSocket.leaveGroup( multicastNetAddress );136 multicastSocket.close();137 }138

Retrieve message stored in received DatagramPacket

Determine whether message is “hello” or “goodbye”

Unsubscribe from MulticastSocket

Page 52: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.13 Class Multicast-ReceivingThread uses threads to add and remove peers (part 5).

Lines 155-157

Lines 172-174

139 // handle exception leaving group140 catch ( IOException ioException ) {141 ioException.printStackTrace();142 }143 144 } // end run145 146 // process hello message from peer147 public void processHello( String peerName, 148 String registryAddress )149 {150 registryAddress += ( "/" + BINDING_NAME );151 synchronized( peerTTLMap )152 {153 154 // if it is a new peer, call peerAdded event155 if ( !peerTTLMap.containsKey( peerName ) ) {156 peerDiscoveryListener.peerAdded( peerName, 157 registryAddress);158 }159 160 // add to map or if present, refresh TTL161 peerTTLMap.put( peerName, new Integer( PEER_TTL ) );162 163 } 164 }165 166 // process goodbye message from peer167 public void processGoodbye( String peerName )168 {169 synchronized( peerTTLMap )170 {171 System.out.println( "Removing peer" + peerName );172 if ( peerTTLMap.containsKey( peerName ) ) {173 peerDiscoveryListener.peerRemoved( peerName );

Add peer to RMI registry

Remove peer to RMI registry

Page 53: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.13 Class Multicast-ReceivingThread uses threads to add and remove peers (part 6).

Line 180

174 peerTTLMap.remove( peerName );175 }176 }177 }178179 // periodically decrements the TTL of peers listed180 private class LeasingThread extends Thread181 {182 public void run()183 {184 while ( keepListening )185 {186 // sleep187 try {188 Thread.sleep( MULTICAST_INTERVAL );189 }190191 // InterruptedException may interrupt Thread Sleep192 catch ( InterruptedException interruptedException ) {193 interruptedException.printStackTrace();194 }195196 // lock hashmap while decrementing TTL values197 synchronized( peerTTLMap ) {198199 // decrement peers200 Iterator peerIterator = 201 peerTTLMap.entrySet().iterator();202203 while ( peerIterator.hasNext() ) {204 // make new TTL of peer205 Map.Entry tempMapEntry = 206 ( Map.Entry ) peerIterator.next();207

Periodically decrement TTL of each peer in peerTTLMap

Page 54: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.13 Class Multicast-ReceivingThread uses threads to add and remove peers (part 7).

Lines 216-220

208 Integer tempIntegerTTL = 209 ( Integer ) tempMapEntry.getValue();210 int tempIntTTL = tempIntegerTTL.intValue();211 212 // decrement TTL213 tempIntTTL--;214 215 // if lease expired, remove peer216 if ( tempIntTTL < 0 ) {217 peerDiscoveryListener.peerRemoved( 218 ( String ) tempMapEntry.getKey() );219 peerIterator.remove();220 }221 222 // otherwise set TTL of peer to new value223 else224 tempMapEntry.setValue( 225 new Integer( tempIntTTL ) );226 227 } // end while iterating through peers228 229 } // end synchronized230 231 } // end while in run method 232 233 } // end run method234 235 } // end class LeasingThread236

If peer’s lease has expired, remove that peer

from peerTTLMap

Page 55: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.13 Class Multicast-ReceivingThread uses threads to add and remove peers (part 8).

237 // stop listening for multicasts238 public void logout()239 {240 // terminate thread241 keepListening = false;242 }243 }

Page 56: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.14 Interface PeerDiscovery-Listener listens for when peers are added and removed from peer groups.

Lines 8-11

1 // PeerDiscoveryListener.java2 // Interface for listening to peerAdded or peerRemoved events3 package com.deitel.advjhtp1.p2p;4 5 public interface PeerDiscoveryListener {6 7 // add peer with given name and ip address 8 public void peerAdded( String name, String peerStubAddress );9 10 // remove peer with given name11 public void peerRemoved( String name );12 13 } Inform PeerDiscovery-

Listener that a peer has entered, or has been removed

from, the multicast group

Page 57: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.15 Modified PeerList enables the user of classes Multicast-ReceivingThread and PeerDiscovery-Listener in the Deitel Instant Messenger (part 1).

Line 25

1 // PeerList.java2 // Starts broadcasting and receiving threads3 // and lists all IM peers in a window4 package com.deitel.advjhtp1.p2p;5 6 // Java core packages7 import java.awt.*;8 import java.awt.event.*;9 import java.net.MalformedURLException;10 import java.util.*;11 import java.util.List;12 import java.io.IOException;13 import java.rmi.*;14 15 // Java extension packages16 import javax.swing.*;17 import javax.swing.event.*;18 19 // Deitel Packages20 import com.deitel.advjhtp1.jini.IM.service.IMService;21 import com.deitel.advjhtp1.jini.IM.client.IMPeerListener;22 import com.deitel.advjhtp1.jini.IM.IMPeerImpl;23 import com.deitel.advjhtp1.jini.IM.IMPeer;24 25 public class PeerList extends JFrame 26 implements PeerDiscoveryListener, IMConstants {27 28 // initialize userName to anonymous29 private String userName = "anonymous";30 private MulticastSendingThread multicastSender; 31 private MulticastReceivingThread multicastReceiver;32 33 // list variables34 private DefaultListModel peerNames; // contains peer names35 private List peerStubAddresses; // contains peer stubs

Modified PeerList uses MulticastReceivingThread and PeerDiscoveryListener

Page 58: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.15 Modified PeerList enables the user of classes Multicast-ReceivingThread and PeerDiscovery-Listener in the Deitel Instant Messenger (part 2).

Lines 39-47

Lines 51-60

36 private JList peerJList;37 38 // add peer name and peer stub to lists39 public void peerAdded( String name, String peerStubAddress )40 {41 // add name to peerNames42 peerNames.addElement( name );43 44 // add stub to peerStubAddresses45 peerStubAddresses.add( peerStubAddress ); 46 47 } // end method peerAdded48 49 50 // removes services from PeerList GUI and data structure51 public void peerRemoved( String name )52 {53 // remove name from peerNames54 int index = peerNames.indexOf( name );55 peerNames.removeElementAt( index );56 57 // remove stub from peerStubAddresses58 peerStubAddresses.remove( index );59 60 } // end method peerRemoved61 62 // constructor63 public PeerList()64 {65 super( "Peer List" );66 67 // get desired userName68 userName = JOptionPane.showInputDialog( 69 PeerList.this, "Please enter your name: " );70

Implement method peer-Added to add peers to lists

Implement method peerRemoved to

remove peers from lists

Page 59: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.15 Modified PeerList enables the user of classes Multicast-ReceivingThread and PeerDiscovery-Listener in the Deitel Instant Messenger (part 3).

Line 89

Lines 102-104

71 // change title of window72 setTitle( userName + "'s Peer List Window" );73 74 // Init List data structures75 peerNames = new DefaultListModel();76 peerStubAddresses = new ArrayList();77 78 // init components79 Container container = getContentPane();80 peerJList = new JList( peerNames );81 peerJList.setVisibleRowCount( 5 );82 JButton connectButton = new JButton( "Connect" );83 84 // do not allow multiple selections85 peerJList.setSelectionMode(86 ListSelectionModel.SINGLE_SELECTION );87 88 // set up event handler for connectButton89 connectButton.addActionListener(90 new ActionListener() {91 92 public void actionPerformed( ActionEvent event )93 {94 int itemIndex = peerJList.getSelectedIndex();95 96 String stubAddress = 97 ( String ) peerStubAddresses.get( itemIndex );98 99 // get RMI reference to IMService and IMPeer100 try {101 102 IMService peerStub = 103 ( IMService ) Naming.lookup( "rmi://" +104 stubAddress );105

Event handler for connecting peers

Obtain reference to remote peer

Page 60: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.15 Modified PeerList enables the user of classes Multicast-ReceivingThread and PeerDiscovery-Listener in the Deitel Instant Messenger (part 4).

106 // set up gui and my peerImpl107 IMPeerListener gui = 108 new IMPeerListener( userName );109 IMPeerImpl me = 110 new IMPeerImpl( userName );111 me.addListener( gui );112 113 // Connect myGui to remote IMPeer object114 IMPeer myPeer = peerStub.connect( me );115 gui.addPeer( myPeer );116 }117 118 // malformedURL passed to lookup119 catch( MalformedURLException exception ) {120 JOptionPane.showMessageDialog121 ( null, "Stub address incorrectly formatted" );122 exception.printStackTrace();123 }124 125 126 // Remote object not bound to remote registry127 catch ( NotBoundException notBoundException ) {128 JOptionPane.showMessageDialog( null, 129 "Remote object not present in Registry" );130 notBoundException.printStackTrace();131 }132 133 // connecting may cause RemoteException134 catch ( RemoteException remoteException ) {135 JOptionPane.showMessageDialog136 ( null, "Couldn't Connect" );137 remoteException.printStackTrace();138 } 139

Page 61: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.15 Modified PeerList enables the user of classes Multicast-ReceivingThread and PeerDiscovery-Listener in the Deitel Instant Messenger (part 5).

140 } // end method ActionPerformed141 142 } // end ActionListener anonymous inner class143 144 ); // end connectButton actionListener145 146 // set up File menu147 JMenu fileMenu = new JMenu( "File" );148 fileMenu.setMnemonic( 'F' );149 150 // about Item151 JMenuItem aboutItem = new JMenuItem( "About..." );152 aboutItem.setMnemonic( 'A' );153 aboutItem.addActionListener( 154 new ActionListener() {155 public void actionPerformed( ActionEvent event )156 {157 JOptionPane.showMessageDialog( PeerList.this, 158 "Deitel Instant Messenger" ,159 "About", JOptionPane.PLAIN_MESSAGE );160 }161 }162 );163 164 fileMenu.add( aboutItem );165 166 // set up JMenuBar and attach File menu167 JMenuBar menuBar = new JMenuBar();168 menuBar.add ( fileMenu );169 setJMenuBar( menuBar );170

Page 62: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.15 Modified PeerList enables the user of classes Multicast-ReceivingThread and PeerDiscovery-Listener in the Deitel Instant Messenger (part 6).

Lines 181-182

171 // handow window closing event172 addWindowListener(173 174 new WindowAdapter(){175 176 public void windowClosing( WindowEvent w )177 {178 System.out.println( "CLOSING WINDOW" );179 180 // disconnects from lookup services181 multicastSender.logout();182 multicastReceiver.logout();183 184 // join threads185 try {186 multicastSender.join();187 multicastReceiver.join();188 }189 catch( InterruptedException interruptedException ) {190 interruptedException.printStackTrace();191 }192 193 System.exit( 0 );194 }195 }196 ); 197 198 // lay out GUI components 199 peerJList.setFixedCellWidth( 100 );200 JPanel inputPanel = new JPanel();201 inputPanel.add( connectButton );202 203 container.add( new JScrollPane( peerJList ) ,204 BorderLayout.NORTH );205 container.add( inputPanel, BorderLayout.SOUTH );

Terminate each thread before closing application

Page 63: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall.All rights reserved.

Outline

Fig. 28.15 Modified PeerList enables the user of classes Multicast-ReceivingThread and PeerDiscovery-Listener in the Deitel Instant Messenger (part 7).

206 207 // Initialize threads208 try {209 210 multicastReceiver = 211 new MulticastReceivingThread( userName, this );212 multicastReceiver.start();213 214 multicastSender = 215 new MulticastSendingThread( userName ); 216 multicastSender.start();217 218 }219 220 // catch all exceptions and inform user of problem221 catch ( Exception managerException ) {222 JOptionPane.showMessageDialog( null, 223 "Error initializing MulticastSendingThread" +224 "or MulticastReceivingThread" );225 managerException.printStackTrace();226 }227 }228 229 public static void main( String args[] )230 {231 PeerList peerlist = new PeerList();232 peerlist.setSize( 100, 170 );233 peerlist.setVisible( true );234 }235 }

Page 64: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.13 Introduction to JXTA

• JXTA– Protocol that promotes interoperability among P2P programs

– Low-level, platform-independent and language-independent

– Attempts to solve problems of P2P applications:• Security/Authentication

• Peer Discovery

• Network Incompatibility

• Platform Incompatibility

Page 65: Chapter 28: Peer-to-Peer Applications and JXTA

2002 Prentice Hall. All rights reserved.

28.13 Introduction to JXTA (cont.)

Protocol Function Peer Discovery Peers use this protocol to find other entities in the JXTA network by searching for

advertisements.

Peer Resolver Peers that help a search process (e.g., higher bandwidth, capacity storage, etc.) implement this protocol.

Peer Information Peers obtain information about other peers via this protocol.

Peer Membership Peers use this protocol to learn about the requirements of groups, how to apply for membership, how to modify their membership and how to quit a group. Authentication and security are implemented through this protocol.

Pipe Binding Peers can connect pipes to one another, via advertisements, through this protocol.

Endpoint Routing Peer routers implement this protocol to provide other routing services to other peers (e.g., tunneling through a firewall).

Fig. 28.16 J XTA low-level protocols.