Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

A P2P library for Android for discovery on local networks using UDP and transfer in general using TCP sockets

License

NotificationsYou must be signed in to change notification settings

ManupaKDU/Near

 
 

Repository files navigation

Near is a P2P library which allows

  • Discovery like Android NSD, though with greater reliability and easier-to-useNearDiscovery API
  • Transfers among clients through an easy-to-useNearConnect API

Sample Usage

Usage Demo GIF

Sample app, with the source codehere isavailable on PlayStore.

NearDiscovery

NearDiscovery takes hostname and a bunch of settings in a builder pattern for the discovery mechanism. A NearDiscovery object allows the following discovery related self-explanatory APIs:

  • void makeDiscoverable(String hostName, String mustMatch /* optional */);
  • void makeNonDiscoverable();
  • void startDiscovery();
  • void stopDiscovery();
  • Set<Host> getAllAvailablePeers();
  • boolean isDiscoverable();
  • boolean isDiscovering();

Here's how the NearDiscovery object is created

privateNearDiscoverymNearDiscovery =newNearDiscovery.Builder()                .setContext(this)                .setDiscoverableTimeoutMillis(DISCOVERABLE_TIMEOUT_MILLIS)                .setDiscoveryTimeoutMillis(DISCOVERY_TIMEOUT_MILLIS)                .setDiscoverablePingIntervalMillis(DISCOVERABLE_PING_INTERVAL_MILLIS)                .setDiscoveryListener(getNearDiscoveryListener(),Looper.getMainLooper())                .setPort(8989)// optional                .setFilter(Regex("filter"))// optional, use with makeDiscoverable("hostName", "filter")                .build();

The Looper passed as the 2nd param of NearDiscovery.Builder.setDiscoveryListener() is for the thread on which the listener, the 1st param, should be called.Sample listener:

@NonNullprivateNearDiscovery.ListenergetNearDiscoveryListener() {returnnewNearDiscovery.Listener() {@OverridepublicvoidonPeersUpdate(Set<Host>hosts) {// Handle updates of peer list here - some peer might have got removed if it wasn't reachable anymore or some new peer might have been added            }@OverridepublicvoidonDiscoveryTimeout() {// This is called after the discovery timeout (specified in the builder) from starting discovery using the startDiscovery()            }@OverridepublicvoidonDiscoveryFailure(Throwablee) {// This is called if discovery could not be started            }@OverridepublicvoidonDiscoverableTimeout() {// This is called after the discoverable timeout (specified in the builder) from becoming discoverable by others using the makeDiscoverable()            }        };    }

NearDiscovery.Builder.setDiscoverablePingIntervalMillis() tells the interval at which each client broadcasts about its existence. The NearDiscovery.Listener.onPeersUpdate() gets called even if a peer is deemed stale, i.e. it's last broadcast received was more than twice the discoverable-ping-interval ago.

The discovery mechanism takes place in background services which do not hold any wakelocks.

NearConnect

A NearConnect object provides P2P mechanism with the following self-explanatory APIs:

  • long send(byte[] bytes, Host peer);
  • void startReceiving();
  • void stopReceiving(boolean abortCurrentTransfers);
  • Set<Host> getPeers();
  • boolean isReceiving();

NearConnect.startReceiving() only tells to startlistening for any incoming transfers, similarly NearConnect.isReceiving() only tells if the client is listening for transfers or not andnot if any data is currently being received.Here's how the NearConnect object is created:

privateNearConnectmNearConnect =newNearConnect.Builder()                .fromDiscovery(mNearDiscovery)                .setContext(this)                .setListener(getNearConnectListener(),Looper.getMainLooper())                .setPort(8990)// optional                .build();

The NearDiscovery object passed in NearConnect.Builder.fromDiscovery() is only to get the list of peers from. Peers can be explicitly provided as well:

privateNearConnectmNearConnect =newNearConnect.Builder()                .forPeers(peers)// Set<Host> peers                .setContext(this)                .setListener(getNearConnectListener(),Looper.getMainLooper())                .setPort(8990)// optional                .build();

Again, the NearConnect.Builder.setListener() takes the Listener as the 1st argument and the Looper on which to call the Listener as the 2nd argument. Here's what the Listener looks like:

@NonNullprivateNearConnect.ListenergetNearConnectListener() {returnnewNearConnect.Listener() {@OverridepublicvoidonReceive(byte[]bytes,finalHostsender) {// Process incoming data here            }@OverridepublicvoidonSendComplete(longjobId) {// jobId is the same as the return value of NearConnect.send(), an approximate epoch time of the send            }@OverridepublicvoidonSendFailure(Throwablee,longjobId) {// handle failed sends here            }@OverridepublicvoidonStartListenFailure(Throwablee) {// This tells that the NearConnect.startReceiving() didn't go through properly.// Common cause would be that another instance of NearConnect is already listening and it's NearConnect.stopReceiving() needs to be called first            }        };    }

It's required to stop listening on a previous instance of NearConnect (using NearConnect.stopReceiving()) so as to start listening on another instance (by using NearConnect.startReceiving()).This is because the same server port is used in each instance (<- could be made configurable later if deemed necessary).

on startReceiving(), and on send() partial wakelocks are held and released on stopReceiving() and on send completion/failure respectively.

Note: NearConnect should work even outside of a local network, except across NAT firewalls.

Getting Started

Add jitpack.io to your root build.gradle

allprojects {    repositories {...        maven { url"https://jitpack.io" }    }}

Then add the dependency in your project build.gradle

dependencies {...    implementation'com.github.adroitandroid:Near:v2.0'...}

You can find the latest versionhere.

Limitations

  • File transfers aren't easy yet. Services are background, API to take notification to start them in foreground, and listener methods to publish updates are on the TODO list.
  • Current Min SDK is 19. Tested with multiple devices and because of code limitation.

License

View full licensehere. In short:

The MIT License is a permissive license that is short and to the point. It lets people do anything they want with your code as long as they provide attribution back to you and don’t hold you liable.

About

A P2P library for Android for discovery on local networks using UDP and transfer in general using TCP sockets

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Kotlin96.5%
  • Java3.5%

[8]ページ先頭

©2009-2025 Movatter.jp