Skip to content

Examples

Marvin Rausch edited this page Apr 1, 2023 · 4 revisions

Example with Usage of ASAPHubManager

The following code snippets are showing all necessary steps to connect your ASAP application with the ASAPHub. These examples were taken from the class HubUsageTests. There are two ways for connection establishment:

1. integrate your application using the ASAPHubManager

This approach shows how to connect to the hub and exchange data using the ASAPHubManager. You should prefer this solution, because a peer an use more than one hub. The ASAPHubManager makes it easy to manage multiple hubs.

boolean multichannel = true;
int hubPort = 6690;
String FORMAT = "app/x-asapHubtest";
String URI = "asap://testuri";

// create hub description with connection settings
HubConnectorDescription localHostHubDescription = new TCPHubConnectorDescriptionImpl("localhost", hubPort, multichannel);
Collection<HubConnectorDescription> hubDescriptions = new ArrayList<>();
hubDescriptions.add(localHostHubDescription);

// define supported formats
Collection<CharSequence> formats = new ArrayList<>();
formats.add(FORMAT);

ASAPPeerFS alicePeer = new ASAPPeerFS("alice", formats);

// send a message
alicePeer.sendASAPMessage(FORMAT, URI, "Hi there".getBytes());

// connect to hub
ASAPEncounterManagerImpl aliceEncounterManager = new ASAPEncounterManagerImpl(aliceASAPPeer);

// setup hub manager and connect to the hub
ASAPHubManager aliceHubManager = ASAPHubManagerImpl.createASAPHubManager(aliceEncounterManager);
aliceHubManager.connectASAPHubs(hubDescriptions, alicePeer, true);

An E2E Test which shows how to start an encounter between Alice and Bob using the ASAPHubManager can be found here.

2. integrate your application using the HubConnector

Alternatively it's also possible to setup a hub connection without using the ASAPHubManager. For this approach it's mandatory to implement a listener which implements the interface NewConnectionListener.

boolean multichannel = true;
int hubPort = 6690;
String host = "localhost";

HubConnector aliceHubConnector = SharedTCPChannelConnectorPeerSide.createTCPHubConnector(host, hubPort);

// add NewConnection listener
HubConnectorTester aliceListener = new HubConnectorTester(ALICE_ID, messageA, messageB, pureBytes);
aliceHubConnector.addListener(aliceListener);

// connect to the ASAPHub
aliceHubConnector.connectHub(ALICE_ID, aliceCanCreateTCPConnections);

// get all peers which are reqistered on the hub
Collection<CharSequence> peerNames = aliceHubConnector.getPeerIDs();

// connect to the peer with the peer-id "bob"
aliceHubConnector.connectPeer("bob");

// disconnect from the hub
aliceHubConnector.disconnectHub();

An E2E Test for this approach can be found here.

Clone this wiki locally