Using Rxnetty on Android
Netty is a Java open source framework provided by JBoss, a communication framework that supports network protocols such as Tcp/udp/http, and is similar to Mina, and is widely used in RPC frameworks. Rxnetty is the Netty Open source framework that supports Rxjava, now let's look at how Rxnetty is used on Android.
Add Rxnetty
To add Rxnetty dependencies in Android Studio:
To add Rxnetty TCP packets to the dependency, there are two problems with compiling directly, the first problem is jar duplication:
com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK THIRD-PARTYFile1: C:\Users\XXX.gradle\caches\modules-2\files-2.1\org.openjdk.jmh\jmh-core\1.11.2\f4f8cd9874f5cdbc272b715a381c57e65f67ddf2\jmh-core-1.11.2.jarFile2: C:\Users\XXX.gradle\caches\modules-2\files-2.1\org.openjdk.jmh\jmh-generator-annprocess\1.11.2\72d854bf76ba5e59596d4c887a6de48e7003bee2\jmh-generator-annprocess-1.11.2.jar
Workaround:
dependencies { ... compile(‘io.reactivex:rxnetty-tcp:0.5.2-RC1‘) { ‘org.openjdk.jmh‘ } ...}
Another problem is that some of the files under meta-inf/in the Netty package are referenced repeatedly.
Workaround:
packagingOptions { ... ‘META-INF/INDEX.LIST‘ ‘META-INF/BenchmarkList‘ ‘META-INF/io.netty.versions.properties‘ ‘META-INF/CompilerHints‘ ... }
The Rxnetty is successfully added to the project module. Next look at how to use Rxnetty.
How to use
Take the TCP protocol example and use the Netty to clearly create the connection steps:
Workergroup =NewNioeventloopgroup (); Bootstrap boot =NewBootstrap (); Boot.group (Workergroup). Channel (niosocketchannel.class). Option (Channeloption.tcp_nodelay,true). Handler (NewChannelinitializer<socketchannel> () {@Override Public void Initchannel(Socketchannel ch)throwsException {Channelpipeline p = ch.pipeline (); P.addlast ("Decoder",NewMessagedecoder ()); P.addlast ("Encoder",NewMessageencoder ()); P.addlast ("Handler",NewMessageHandler ()); } }); Channelfuture f = boot.connect ("localhost",8888). syncuninterruptibly (); Channel = F.channel ();
The custom protocol requires us to implement our own encoding and decoding handler, as well as the final processing of the data MessageHandler :
@Sharablepublicclass MessageHandler extends SimpleChannelInboundHandler<Message> { @Override publicvoidmessageReceived(ChannelHandlerContext ctx, Message msg) throws Exception { //处理消息 }}
Can not be implemented in Rxnetty MessageHandler , because the registered observer can get the final decoded protocol object.
Here's how Rxnetty creates a connection:
Connection<string, string> mconnection; PublicObservable<boolean>Connect(FinalString URL,Final intPort) {returnObservable.create (NewObservable.onsubscribe<boolean> () {@Override Public void Pager(Finalsubscriber<?Superboolean> subscriber) {tcpclient.newclient (URL, port). <string, String>addchannelhandlerlast ("Decoder",NewFunc0<channelhandler> () {@Override PublicChannelhandlerPager() {return NewStringdecoder (); }}). <string, String>addchannelhandlerlast ("Encoder",NewFunc0<channelhandler> () {@Override PublicChannelhandlerPager() {return NewStringencoder (); }}). Createconnectionrequest (). Subscribe (NewObserver<connection<string, string>> () {@Override Public void oncompleted() {subscriber.oncompleted (); }@Override Public void OnError(Throwable e) {Subscriber.onerror (e); }@Override Public void OnNext(connection<string, string> Connection) {mconnection = connection; Subscriber.onnext (true); } }); } }); }
The above TCP client creates a string decoder, a string encoder, and then creates a link that saves the linked object to a convenient post after the link is created connection mConnection , and notifies the Subscriber that the socket connection was successful.
In Android it is not possible to create a network link in the UI thread, even if the InetSocketAddress class cannot be created in the UI thread TcpClient.newClient(url, port)...createConnectionRequest() itself, Observable but because the class is newClient(url, port) created in the method, the InetSocketAddress Android harsh mode will report an exception, So the TcpClient method that creates the link above is wrapped up in the outer layer Observable , allowing it to run on other non-UI threads, such as the IO thread, to create the socket link normally.
The method used to receive the data and send the data also returns a observable with the following code:
publicreceive() { ifnull) { return mConnection.getInput(); } returnnull; } publicsend(String s) { return mConnection.writeString(Observable.just(s)); }
To test the client code for the method above:
Public void rxnettyclienttest() {Connect ("localhost",60000). Subscribe (NewObserver<boolean> () {@Override Public void oncompleted() { }@Override Public void OnError(Throwable e) {//reconnectObservable.timer (1, timeunit.seconds). Subscribe (NewAction1<long> () {@Override Public void Pager(Long along) {if(Mconnection! =NULL) Mconnection.closenow (); Rxnettyclienttest (); } }); System.out.println ("Reconnect"); }@Override Public void OnNext(Boolean Aboolean) {//send DataSend"Hello world!"). Subscribe (NewAction1<void> () {@Override Public void Pager(Void aVoid) {System.out.println ("Send Success!"); } });//receive DataReceive (). Subscribe (NewObserver<string> () {@Override Public void oncompleted() { }@Override Public void OnError(Throwable e) {//reconnectObservable.timer (1, timeunit.seconds). Subscribe (NewAction1<long> () {@Override Public void Pager(Long along) {if(Mconnection! =NULL) Mconnection.closenow (); Rxnettyclienttest (); } }); System.out.println ("Reconnect"); }@Override Public void OnNext(String s) {System.out.println ("Receive:"+ s); } }); } }); }
The above code includes the main functions of reading, writing data, and re-connecting.
Then the code to create the service side:
Public void rxnettyservertest() {tcpserver<string, string> server; Server = Tcpserver.newserver (60000). <string, String>addchannelhandlerlast ("String-decoder",NewFunc0<channelhandler> () {@Override PublicChannelhandlerPager() {return NewStringdecoder (); }}). <string, String>addchannelhandlerlast ("String-encoder",NewFunc0<channelhandler> () {@Override PublicChannelhandlerPager() {return NewStringencoder (); }}). Start (NewConnectionhandler<string, string> () {@Override PublicObservable<void>Handle(connection<string, string> newconnection) {returnNewconnection.writestringandflushoneach (Newconnection.getinput (). Map (NewFunc1<string, string> () {@Override PublicStringPager(String s) {System.out.println ("Receive:", T);return "Echo=>"+ S; } })); } }); Server.awaitshutdown (); }
Server-side code is relatively simple, directly echo client data sent.
With regard to threads, it is necessary to handle the network in Android subscribeOn(Schedulers.io()) , if necessary in the UI thread observeOn(AndroidSchedulers.mainThread()) .
Finally, the use of Rxnetty on Android is mostly due to the lack of a suitable socket client framework, Rxnetty also supports the HTTP protocol, the optional framework of the HTTP protocol on Android is more, so it is not introduced here, Want to know can come here rxnetty.
Using Rxnetty on Android