Skip to content

Commit

Permalink
添加socket通讯
Browse files Browse the repository at this point in the history
  • Loading branch information
yuzhijun committed Jun 14, 2017
1 parent cea2334 commit 84f54a0
Show file tree
Hide file tree
Showing 17 changed files with 815 additions and 6 deletions.
32 changes: 31 additions & 1 deletion app/src/main/java/com/lenovohit/lrouter/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
Expand All @@ -19,13 +20,14 @@
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private Handler handler;

private Button button1;
private Button button2;
private Button button3;
private Button button4;
private Button button5;
private Button button6;

@Override
protected void onCreate(Bundle savedInstanceState) {
Expand All @@ -37,11 +39,18 @@ protected void onCreate(Bundle savedInstanceState) {
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
button6 = (Button) findViewById(R.id.button6);

initEvent();
}

private void initEvent(){
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this,(String)msg.obj,Toast.LENGTH_SHORT).show();
}
};
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Expand Down Expand Up @@ -151,5 +160,26 @@ public void accept(Throwable throwable) throws Exception {
}
}
});

button6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LocalRouter.getInstance(LRouterAppcation.getInstance())
.socketNavigation("Hello-socket".getBytes(), 10000, new IRequestCallBack() {
@Override
public void onSuccess(final String result) {
Message message = new Message();
message.obj = result;
message.what =1;
handler.sendMessage(message);
}

@Override
public void onFailure(Exception e) {

}
});
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,5 @@ public class MainAnologyApplication extends AnologyApplication {
@Override
public void onCreate() {//在类application类里面将provider注册进本地路由内,每个模块有一个provider对应多个action
super.onCreate();
// LocalRouter.getInstance(mApplication).registerProvider("main",new MainProvider());
}
}
15 changes: 15 additions & 0 deletions app/src/main/java/com/lenovohit/lrouter/SocketAction.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.lenovohit.lrouter;

import com.lenovohit.lrouter_api.annotation.ioc.Action;
import com.lenovohit.lrouter_api.core.socket.server.LRSocketAction;

/**
* Created by yuzhijun on 2017/6/13.
*/
@Action(name = "socketAction",provider = "main")
public class SocketAction extends LRSocketAction{
@Override
public String socketInvoke(String receiveStr) {
return receiveStr;
}
}
9 changes: 9 additions & 0 deletions app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,13 @@
tools:layout_editor_absoluteY="28dp"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"/>

<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Socket通讯"
tools:layout_editor_absoluteY="28dp"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"/>
</LinearLayout>
5 changes: 3 additions & 2 deletions lrouter-api/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lenovohit.lrouter_api"
>
package="com.lenovohit.lrouter_api">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:label="@string/app_name"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,10 @@ public void onCreate() {
setAnologyApplicaiton();
//调用各类application的生命周期onCreate
invokeOnCreate();
//扫描所有类注入带注解的action,provider,interceptor等类
PackageScanner.scan(mInstance);
if (RemoteRouter.PROCESS_NAME.equalsIgnoreCase(ProcessUtil.getProcessName(this, ProcessUtil.getMyProcessId()))){
//扫描所有类注入带注解的action,provider,interceptor等类
PackageScanner.scan(mInstance);
}
// }
// }).start();
}catch (Exception e){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.lenovohit.lrouter_api.IRemoteRouterAIDL;
import com.lenovohit.lrouter_api.base.LRouterAppcation;
import com.lenovohit.lrouter_api.core.callback.IRequestCallBack;
import com.lenovohit.lrouter_api.core.socket.LRSocketThreadManager;
import com.lenovohit.lrouter_api.exception.LRException;
import com.lenovohit.lrouter_api.intercept.ioc.Navigation;
import com.lenovohit.lrouter_api.utils.DefaultPoolExecutor;
Expand All @@ -19,6 +20,7 @@
import com.lenovohit.lrouter_api.utils.ProcessUtil;

import java.lang.ref.SoftReference;
import java.net.InetAddress;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
Expand All @@ -40,6 +42,8 @@ public class LocalRouter {
private static ExecutorService threadPool = null;
//本地路由持有各个模块所有的provider,可能有多个进程localRouter访问所以用ConcurrentHashMap
private ConcurrentHashMap<String,LRProvider> mProviderHashmap = null;
//用于保存对应端口的Manager
private ConcurrentHashMap<Integer,LRSocketThreadManager> mSocktManagerHashMap = null;
//用于跨进程访问远程路由
public IRemoteRouterAIDL mRemoteRouterAIDL;
//空的task
Expand All @@ -48,6 +52,7 @@ public class LocalRouter {
protected LocalRouter(LRouterAppcation context) {
mLRouterAppcation = context;
mProviderHashmap = new ConcurrentHashMap<>();
mSocktManagerHashMap = new ConcurrentHashMap<>();
mProcessName = ProcessUtil.getProcessName(context, ProcessUtil.getMyProcessId());
if (mLRouterAppcation.needMultipleProcess() && !RemoteRouter.PROCESS_NAME.equals(mProcessName)) {
connect2RemoteRouter(mProcessName);
Expand Down Expand Up @@ -179,6 +184,28 @@ public ListenerFutureTask navigation(Context context, LRouterRequest request) th
return futureTask;
}

/**
* 通过socket访问
* */
public synchronized void socketNavigation(final byte[] msg, final int hostPort, final IRequestCallBack requestCallBack){
new Thread(new Runnable() {
@Override
public void run() {
try{
LRSocketThreadManager socketThreadManager = mSocktManagerHashMap.get(hostPort);
if (null == socketThreadManager){
InetAddress ia = InetAddress.getLocalHost();
socketThreadManager = new LRSocketThreadManager(ia.getHostAddress(),hostPort,requestCallBack);
mSocktManagerHashMap.put(hostPort,socketThreadManager);
}
socketThreadManager.sendMsg(msg,mHandler);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}

//检查远程服务是否连接
public boolean checkRemoteRouterConnect(){
boolean result = false;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.lenovohit.lrouter_api.core.socket;

/**
* 用于放服务器连接的常量
* Created by yuzhijun on 2017/6/13.
*/
public class Const {
//读超时时间
public final static int SOCKET_READ_TIMOUT = 15 * 1000;
//如果没有连接无服务器。读线程的sleep时间
public final static int SOCKET_SLEEP_SECOND = 3 ;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.lenovohit.lrouter_api.core.socket;

import android.os.Handler;

import com.lenovohit.lrouter_api.core.callback.IRequestCallBack;
import com.lenovohit.lrouter_api.core.socket.client.LRSocketClient;
import com.lenovohit.lrouter_api.core.socket.client.LRSocketReceiveThread;
import com.lenovohit.lrouter_api.core.socket.client.LRSocketSendThread;

/**
* 线程管理器
* Created by yuzhijun on 2017/6/13.
*/
public class LRSocketThreadManager {
private LRSocketThreadManager mSocketThreadManager = null;
private LRSocketReceiveThread mReceiveThread = null;
private LRSocketSendThread mSendThread = null;
private LRSocketClient mLRSocketClient = null;

public LRSocketThreadManager(String hostIP,int hostPort,IRequestCallBack requestCallBack){
mLRSocketClient = new LRSocketClient(hostIP,hostPort);
mReceiveThread = new LRSocketReceiveThread(hostIP,hostPort,mLRSocketClient,requestCallBack);
mSendThread = new LRSocketSendThread(hostIP,hostPort,mLRSocketClient);
startThreads();
}

private void startThreads(){
mReceiveThread.start();
mSendThread.start();
mReceiveThread.setStart(true);
mSendThread.setStart(true);
}

public void stopThreads() {
mReceiveThread.setStart(false);
mSendThread.setStart(false);
}

public void releaseInstance() {
if (mSocketThreadManager != null) {
mSocketThreadManager.stopThreads();
mSocketThreadManager = null;
}
}

public void sendMsg(byte [] buffer, Handler handler) {
MsgObject entity = new MsgObject(buffer, handler);
mSendThread.addMsg2Queue(entity);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.lenovohit.lrouter_api.core.socket;

import android.os.Handler;

/**
* 发送的实体
* Created by yuzhijun on 2017/6/13.
*/
public class MsgObject {
//要发送的消息
private byte [] bytes;
//错误处理的handler
private Handler mHandler;

public MsgObject(byte [] bytes, Handler handler){
this.bytes = bytes;
mHandler = handler;
}

public byte [] getBytes()
{
return this.bytes;
}

public Handler getHandler()
{
return mHandler;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package com.lenovohit.lrouter_api.core.socket.client;

import com.lenovohit.lrouter_api.core.socket.Const;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
* 用于跟服务端(各个模块)连接
* Created by yuzhijun on 2017/6/13.
*/
public class LRSocketClient {
// 信道选择器
private Selector selector;
// 与服务器通信的信道
SocketChannel socketChannel;
//连接的服务器IP地址
private String hostIP;
//连接的服务器监听的接口
private int hostPort;

private boolean init = false;

public LRSocketClient(String hostIP,int hostPort){
this.hostIP = hostIP;
this.hostPort = hostPort;

try{
init();
this.init = true;
}catch (IOException e){
this.init = false;
e.printStackTrace();
}catch (Exception e){
this.init = false;
e.printStackTrace();
}
}

/**
* 初始化
* @throws IOException
* */
public void init() throws IOException{
boolean done = false;

try {
// 打开监听信道并设置为非阻塞模式
socketChannel = SocketChannel.open(new InetSocketAddress(hostIP, hostPort));
if (socketChannel != null) {
socketChannel.socket().setTcpNoDelay(false);
socketChannel.socket().setKeepAlive(true);
// 设置 读socket的timeout时间
socketChannel.socket().setSoTimeout(Const.SOCKET_READ_TIMOUT);
socketChannel.configureBlocking(false);

// 打开并注册选择器到信道
selector = Selector.open();
if (selector != null) {
socketChannel.register(selector, SelectionKey.OP_READ);
done = true;
}
}
}finally {
if (!done && selector != null) {
selector.close();
}
if (!done) {
socketChannel.close();
}
}
}

/**
* 发送数据
* @param bytes
* @throws IOException
*/
public void sendMsg(byte[] bytes) throws IOException {
ByteBuffer writeBuffer = ByteBuffer.wrap(bytes);

if (socketChannel == null) {
throw new IOException();
}
socketChannel.write(writeBuffer);
}

/**
* Socket连接是否是正常的
*/
public boolean isConnect() {
boolean isConnect = false;
if (this.init) {
isConnect = this.socketChannel.isConnected();
}
return isConnect;
}

public synchronized Selector getSelector() {
return this.selector;
}
}
Loading

0 comments on commit 84f54a0

Please sign in to comment.