# autobahn-java **Repository Path**: hihopeorg/autobahn-java ## Basic Information - **Project Name**: autobahn-java - **Description**: No description available - **Primary Language**: Java - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-02-27 - **Last Updated**: 2022-08-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # autobahn-java **本项目是基于开源项目autobahn-java进行ohos化的移植和开发的,可以通过项目标签以及github地址(https://github.com/crossbario/autobahn-java )追踪到原项目版本** #### 项目介绍 - 项目名称:WebSocket和WAMP协议客户端 - 所属系列:ohos的第三方组件适配移植 - 功能: 1.WebSocket协议:WebSocket层使用基于回调的用户API,专门为ohos编写。例如,它不在主(UI)线程上运行任何网络内容; 2.Web应用程序消息传递协议(WAMP):WAMP层使用Java 8 CompletableFuture进行WAMP操作(调用,注册,发布和订阅),并使用观察者模式处理WAMP会话,订阅和注册生命周期事件; - 项目移植状态:完成 - 调用差异:无 - 项目作者和维护人:hihope - 联系方式:hihope@hoperun.com - 原项目Doc地址:https://github.com/crossbario/autobahn-java - 原项目基线版本:v20.7.1,sha1:c48c8d125f7eaa4778683e72cd49af14e6a8ba06 - 编程语言:Java #### 效果展示 #### 安装教程 方法1. 1. 添加har包到lib文件夹内。 2. 在entry的build.gradle内添加如下代码。 ``` implementation fileTree(dir: 'libs', include: ['*.jar', '*.har' , '*.so']) ``` 3. 编译libsodium,生成libsodium-release.har,放在entry中的libs目录。 方法2. 1. 在工程的build.gradle的allprojects中,添加HAR所在的Maven仓地址 ``` repositories { maven { url 'http://106.15.92.248:8081/repository/Releases/' } } ``` 2. 在应用模块的build.gradle的dependencies闭包中,添加如下代码: ``` dependencies { implementation 'io.crossbar.autobahn:autobahn-ohos:1.0.1' implementation 'io.crossbar.autobahn:libsodium:1.0.1' } ``` #### 使用说明 1. WebSocket on ohos ``` 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); } }); ``` 2. Show me some code The code in demo-gallery contains some examples on how to use the autobahn library, it also contains convenience methods to use. Below is a basic set of code examples showing all 4 WAMP actions. ### Subscribe to a topic ``` java public void demonstrateSubscribe(Session session, SessionDetails details) { // Subscribe to topic to receive its events. CompletableFuture 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 args, Map kwargs, EventDetails details) { System.out.println(String.format("Got event: %s", args.get(0))); } ``` Since we are only accessing `args` in onEvent(), we could simplify it like: ``` java private void onEvent(List args) { System.out.println(String.format("Got event: %s", args.get(0))); } ``` ### Publish to a topic ``` java public void demonstratePublish(Session session, SessionDetails details) { // Publish to a topic that takes a single arguments List args = Arrays.asList("Hello World!", 900, "UNIQUE"); CompletableFuture 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; }); } ``` A simpler call would look like: ``` java public void demonstratePublish(Session session, SessionDetails details) { CompletableFuture pubFuture = session.publish("com.myapp.hello", "Hi!"); ... } ``` ### Register a procedure ``` java public void demonstrateRegister(Session session, SessionDetails details) { // Register a procedure. CompletableFuture regFuture = session.register("com.myapp.add2", this::add2); regFuture.thenAccept(registration -> System.out.println("Successfully registered procedure: " + registration.procedure)); } private CompletableFuture add2( List args, Map kwargs, InvocationDetails details) { int res = (int) args.get(0) + (int) args.get(1); List arr = new ArrayList<>(); arr.add(res); return CompletableFuture.completedFuture(new InvocationResult(arr)); } ``` A very precise `add2` may look like: ``` java private List add2(List args, InvocationDetails details) { int res = args.get(0) + args.get(1); return Arrays.asList(res, details.session.getID(), "Java"); } ``` ### Call a procedure ``` java public void demonstrateCall(Session session, SessionDetails details) { // Call a remote procedure. CompletableFuture callFuture = session.call("com.myapp.add2", 10, 20); callFuture.thenAccept(callResult -> System.out.println(String.format("Call result: %s", callResult.results.get(0)))); } ``` Calling procedure with variable data type parameters ``` java 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 args = new ArrayList<>(); args.add(var1); args.add(var2); args.add(var3); CompletableFuture callFuture = session.call("com.myapp.myproc", args); callFuture.thenAccept(callResult -> System.out.println(String.format("Call result: %s", callResult.results.get(0)))); } ``` ### Connecting the dots ``` java 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 exitInfoCompletableFuture = client.connect(); } ``` ### Authentication Authentication is simple, we just need to create an object of the desired authenticator and pass that to the Client ### Ticket Auth ``` java public void main() { ... IAuthenticator authenticator = new TicketAuth(authid, ticket); Client client = new Client(session, url, realm, authenticator); CompletableFuture exitInfoCompletableFuture = client.connect(); } ``` ### Challenge Response Auth ``` java public void main() { ... IAuthenticator authenticator = new ChallengeResponseAuth(authid, secret); Client client = new Client(session, url, realm, authenticator); CompletableFuture exitInfoCompletableFuture = client.connect(); } ``` ### Cryptosign Auth ``` java public void main() { ... IAuthenticator authenticator = new CryptosignAuth(authid, privkey, pubkey); Client client = new Client(session, url, realm, authenticator); CompletableFuture exitInfoCompletableFuture = client.connect(); } ``` You can also provide a list of Authenticators ``` java public void main() { ... List 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 exitInfoCompletableFuture = client.connect(); } ``` Autobahn also supports POJOs Here is how to call a remote procedure that returns a list of Person POJOs ``` java // Call a remote procedure that returns a Person with id 1 CompletableFuture callFuture = mSession.call("com.example.get_person", 1); callFuture.whenCompleteAsync((person, throwable) -> { if (throwable != null) { // handle error } else { // success! // do something with person } }, mExecutor); ``` ``` java // call a remote procedure that returns a List CompletableFuture> callFuture = mSession.call( // remote procedure to call "com.example.get_persons_by_department", // positional call arguments new ArrayList() {List.of("department-7")}, // call return type new TypeReference>() {} ); callFuture.whenCompleteAsync((persons, throwable) -> { if (throwable != null) { // handle error } else { // success! for (Person person: persons) { // do something with person } } }, mExecutor); ``` Also register a procedure that returns a Person ``` java private Person get_person() { return new Person("john", "doe", "hr"); } private void main() { CompletableFuture 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)); }); } ``` #### 版本迭代 - v1.0.1 #### 版权和许可信息 - The MIT License (MIT)