Pustaka klien menyediakan WAMP di Java 8 (Netty) dan Android, ditambah WebSocket (aman) untuk Android.
Autobahn|Java adalah subproyek dari proyek Autobahn dan menyediakan implementasi klien sumber terbuka untuk
berjalan di Android dan Netty/Java8/JVM.
Lapisan WebSocket menggunakan API pengguna berbasis panggilan balik, dan secara khusus ditulis untuk Android. Misalnya itu tidak menjalankan hal-hal jaringan apa pun di thread utama (UI).
Lapisan WAMP menggunakan Java 8 CompletableFuture untuk tindakan WAMP (memanggil, mendaftar, menerbitkan, dan berlangganan) dan pola Pengamat untuk sesi WAMP, peristiwa siklus hidup langganan dan pendaftaran.
Perpustakaan ini berlisensi MIT, dikelola oleh Proyek Crossbar.io, diuji menggunakan AutobahnTestsuite dan diterbitkan sebagai JAR ke Maven dan sebagai image rantai alat Docker ke Dockerhub.
Ambil melalui Maven:
< dependency >
< groupId >io.crossbar.autobahn</ groupId >
< artifactId >autobahn-android</ artifactId >
< version >21.7.1</ version >
</ dependency >
Gradasi:
dependencies {
implementation ' io.crossbar.autobahn:autobahn-android:21.7.1 '
}
Untuk sistem non-android gunakan artefakID autobahn-java
atau cukup Download JAR terbaru
Klien demo mudah dijalankan, Anda hanya perlu menginstal make
dan docker
untuk menjalankannya.
$ make crossbar # Starts crossbar in a docker container
$ make python # Starts a python based WAMP components that provides calls for the Java demo client
dan akhirnya
$ make java # Starts the java (Netty) based demo client that performs WAMP actions
Kode di galeri demo berisi beberapa contoh cara menggunakan perpustakaan autobahn, juga berisi metode kemudahan untuk digunakan. Di bawah ini adalah kumpulan contoh kode dasar yang menunjukkan keempat tindakan WAMP.
public void demonstrateSubscribe ( Session session , SessionDetails details ) {
// Subscribe to topic to receive its events.
CompletableFuture < Subscription > subFuture = session . subscribe ( "com.myapp.hello" ,
this :: onEvent );
subFuture . whenComplete (( subscription , throwable ) -> {
if ( throwable == null ) {
// We have successfully subscribed.
System . out . println ( "Subscribed to topic " + subscription . topic );
} else {
// Something went bad.
throwable . printStackTrace ();
}
});
}
private void onEvent ( List < Object > args , Map < String , Object > kwargs , EventDetails details ) {
System . out . println ( String . format ( "Got event: %s" , args . get ( 0 )));
}
Karena kita hanya mengakses args
di onEvent(), kita dapat menyederhanakannya seperti:
private void onEvent ( List < Object > args ) {
System . out . println ( String . format ( "Got event: %s" , args . get ( 0 )));
}
public void demonstratePublish ( Session session , SessionDetails details ) {
// Publish to a topic that takes a single arguments
List < Object > args = Arrays . asList ( "Hello World!" , 900 , "UNIQUE" );
CompletableFuture < Publication > pubFuture = session . publish ( "com.myapp.hello" , args );
pubFuture . thenAccept ( publication -> System . out . println ( "Published successfully" ));
// Shows we can separate out exception handling
pubFuture . exceptionally ( throwable -> {
throwable . printStackTrace ();
return null ;
});
}
Panggilan yang lebih sederhana akan terlihat seperti:
public void demonstratePublish ( Session session , SessionDetails details ) {
CompletableFuture < Publication > pubFuture = session . publish ( "com.myapp.hello" , "Hi!" );
...
}
public void demonstrateRegister ( Session session , SessionDetails details ) {
// Register a procedure.
CompletableFuture < Registration > regFuture = session . register ( "com.myapp.add2" , this :: add2 );
regFuture . thenAccept ( registration ->
System . out . println ( "Successfully registered procedure: " + registration . procedure ));
}
private CompletableFuture < InvocationResult > add2 (
List < Object > args , Map < String , Object > kwargs , InvocationDetails details ) {
int res = ( int ) args . get ( 0 ) + ( int ) args . get ( 1 );
List < Object > arr = new ArrayList <>();
arr . add ( res );
return CompletableFuture . completedFuture ( new InvocationResult ( arr ));
}
add2
yang sangat tepat mungkin terlihat seperti:
private List < Object > add2 ( List < Integer > args , InvocationDetails details ) {
int res = args . get ( 0 ) + args . get ( 1 );
return Arrays . asList ( res , details . session . getID (), "Java" );
}
public void demonstrateCall ( Session session , SessionDetails details ) {
// Call a remote procedure.
CompletableFuture < CallResult > callFuture = session . call ( "com.myapp.add2" , 10 , 20 );
callFuture . thenAccept ( callResult ->
System . out . println ( String . format ( "Call result: %s" , callResult . results . get ( 0 ))));
}
Memanggil prosedur dengan parameter tipe data variabel
public void demonstrateCall ( Session session , SessionDetails details ) {
// Call a remote procedure.
byte [] var1 = new byte [ 20 ];
String var2 = "A sample text" ;
int var3 = 99 ;
List < Object > args = new ArrayList <>();
args . add ( var1 );
args . add ( var2 );
args . add ( var3 );
CompletableFuture < CallResult > callFuture = session . call ( "com.myapp.myproc" , args );
callFuture . thenAccept ( callResult ->
System . out . println ( String . format ( "Call result: %s" , callResult . results . get ( 0 ))));
}
public void main () {
// Create a session object
Session session = new Session ();
// Add all onJoin listeners
session . addOnJoinListener ( this :: demonstrateSubscribe );
session . addOnJoinListener ( this :: demonstratePublish );
session . addOnJoinListener ( this :: demonstrateCall );
session . addOnJoinListener ( this :: demonstrateRegister );
// finally, provide everything to a Client and connect
Client client = new Client ( session , url , realm );
CompletableFuture < ExitInfo > exitInfoCompletableFuture = client . connect ();
}
Otentikasinya sederhana, kita hanya perlu membuat objek autentikator yang diinginkan dan meneruskannya ke Klien
public void main () {
...
IAuthenticator authenticator = new TicketAuth ( authid , ticket );
Client client = new Client ( session , url , realm , authenticator );
CompletableFuture < ExitInfo > exitInfoCompletableFuture = client . connect ();
}
public void main () {
...
IAuthenticator authenticator = new ChallengeResponseAuth ( authid , secret );
Client client = new Client ( session , url , realm , authenticator );
CompletableFuture < ExitInfo > exitInfoCompletableFuture = client . connect ();
}
public void main () {
...
IAuthenticator authenticator = new CryptosignAuth ( authid , privkey , pubkey );
Client client = new Client ( session , url , realm , authenticator );
CompletableFuture < ExitInfo > exitInfoCompletableFuture = client . connect ();
}
Anda juga dapat memberikan daftar Authenticator
public void main () {
...
List < IAuthenticator > authenticators = new ArrayList <>();
authenticators . add ( new TicketAuth ( authid , ticket ));
authenticators . add ( new CryptosignAuth ( authid , privkey , pubkey ));
Client client = new Client ( session , url , realm , authenticators );
CompletableFuture < ExitInfo > exitInfoCompletableFuture = client . connect ();
}
Autobahn juga mendukung POJO
Berikut ini cara memanggil prosedur jarak jauh yang mengembalikan daftar POJO Orang
// Call a remote procedure that returns a Person with id 1
CompletableFuture < Person > callFuture = mSession . call ( "com.example.get_person" , 1 );
callFuture . whenCompleteAsync (( person , throwable ) -> {
if ( throwable != null ) {
// handle error
} else {
// success!
// do something with person
}
}, mExecutor );
// call a remote procedure that returns a List<Person>
CompletableFuture < List < Person >> callFuture = mSession . call (
// remote procedure to call
"com.example.get_persons_by_department" ,
// positional call arguments
new ArrayList < Object >() { List . of ( "department-7" )},
// call return type
new TypeReference < List < Person >>() {}
);
callFuture . whenCompleteAsync (( persons , throwable ) -> {
if ( throwable != null ) {
// handle error
} else {
// success!
for ( Person person : persons ) {
// do something with person
}
}
}, mExecutor );
Daftarkan juga prosedur yang mengembalikan Seseorang
private Person get_person () {
return new Person ( "john" , "doe" , "hr" );
}
private void main () {
CompletableFuture < Registration > regFuture = session . register (
"io.crossbar.example.get_person" , this :: get_person );
regFuture . whenComplete (( registration , throwable ) -> {
System . out . println ( String . format (
"Registered procedure %s" , registration . procedure ));
});
}
Contoh gema
WebSocketConnection connection = new WebSocketConnection ();
connection . connect ( "wss://echo.websocket.org" , new WebSocketConnectionHandler () {
@ Override
public void onConnect ( ConnectionResponse response ) {
System . out . println ( "Connected to server" );
}
@ Override
public void onOpen () {
connection . sendMessage ( "Echo with Autobahn" );
}
@ Override
public void onClose ( int code , String reason ) {
System . out . println ( "Connection closed" );
}
@ Override
public void onMessage ( String payload ) {
System . out . println ( "Received message: " + payload );
connection . sendMessage ( payload );
}
});
Membangun Autobahn cukup sederhana
Untuk Android, kami menyarankan untuk menggunakan Android Studio. Cukup impor proyek di Android Studio, ini akan memberi tahu Anda jika ada dependensi yang hilang, instal, lalu buat proyek dari Build > Rebuild Project
dan Anda akan memiliki artefak aar di autobahn/build/outputs/aar/
Untuk menghasilkan build untuk sistem non-Android, pastikan Anda telah menginstal docker dan make, lalu gunakan perintah run di bawah ini pada direktori root proyek
make build_autobahn
dan itu akan menampilkan file jar di autobahn/build/libs/
.
Hubungi kami dengan bergabung di forum kami.
Versi 1 perpustakaan ini masih dalam repo di sini, namun tidak lagi dipertahankan.
Versi 1 hanya mendukung WebSocket yang tidak aman di Android dan hanya mendukung WAMP v1.
Kedua masalah ini telah diperbaiki di Autobahn|Java versi (saat ini).