
org.caiguoqing.uyuni.rpc.client.socketclient.SocketProxyHandler Maven / Gradle / Ivy
The newest version!
/**
*
*/
package org.caiguoqing.uyuni.rpc.client.socketclient;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.http.util.NetUtils;
import org.caiguoqing.uyuni.rpc.pub.InterCount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author org.caiguoqing
*
*/
public class SocketProxyHandler implements InvocationHandler {
private Logger logger = LoggerFactory.getLogger(SocketProxyHandler.class);
private int port = 0;
private String host;
private InterCount interCount;
private int sleep = 1000*3;
private Socket socket;
private Throwable exception;
private ObjectOutputStream output;
private ObjectInputStream input;
private volatile boolean isContinue = false;
private volatile boolean isSendHeart = false;
private String localAddress;
public SocketProxyHandler(String host,int port,InterCount interCount){
this.host = host;
this.port = port;
this.interCount = interCount;
init();
monitor();
}
private void init(){
try {
socket = new Socket(host, port);
output = new ObjectOutputStream(socket.getOutputStream());
input = new ObjectInputStream(socket.getInputStream());
localAddress = socket.getLocalAddress().getHostAddress();
} catch (UnknownHostException e) {
exception = e;
e.printStackTrace();
} catch (IOException e) {
exception = e;
e.printStackTrace();
}
}
private void closeSocket(){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void monitor(){
isContinue = true;
new Thread(new Runnable() {
public void run() {
while(isContinue){
try {
if(isSendHeart){
output.writeObject("uyuni_heartbeat");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
if(exception != null){
throw exception;
}
isSendHeart = false;
String inter = method.getDeclaringClass().getName();
String methodName = method.getName();
interCount.add(localAddress + " -> " + inter + "." + methodName);
output.writeObject(inter);
output.writeObject(methodName);
output.writeObject(method.getParameterTypes());
output.writeObject(arguments);
isSendHeart = true;
Object result = input.readObject();
if (result instanceof Throwable) {
throw (Throwable) result;
}
return result;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy