`
dyccsxg
  • 浏览: 202165 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
社区版块
存档分类

Java远程方法调用

    博客分类:
  • Java
阅读更多
// 参考:http://book.csdn.net/bookfiles/269/10026911927.shtml
// remote.server.SimpleServer.java
package remote.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import share.call.Call;


/**
 *@date 2010-3-13 下午04:38:44
 *@author dycc
 */
public class SimpleServer {
	private Map<String,Object> objs = new HashMap<String,Object>();
	private ObjectInputStream in;
	private ObjectOutputStream out;
	
	public void service()throws IOException{
		ServerSocket server_socket = new ServerSocket(8002);
		System.out.println("----- server started. -----");
		while(true){
			try{
    			Socket socket = server_socket.accept();
    			// ObjectInputStream 会发生阻塞!!
    			in = new ObjectInputStream(socket.getInputStream());
    			Call call = (Call)in.readObject();
    			System.out.println("-- get call [" + call.getClassName()
    					           + ":" + call.getMethodName() + "]");
    			call = invoke(call);
    			out = new ObjectOutputStream(socket.getOutputStream());
    			out.writeObject(call);
    			out.flush();
			} catch(Exception e){
				e.printStackTrace();
			} finally{
				try{
					if(in != null){
						in.close();
					}
					if(out != null){
						out.close();
					}
				} catch(Exception e){
				}
			}
		}
	}
	
	public Call invoke(Call call){
		Object obj = objs.get(call.getClassName());
		if(obj == null){
			try {
	            obj = Class.forName(call.getClassName()).newInstance();
	            objs.put(call.getClassName(), obj);
            } catch (Exception e) {
	            e.printStackTrace();
            }
		}
		try {
	        Method method = obj.getClass().getMethod(
	        			    call.getMethodName(),
	        			    call.getParamTypes());
	        Object result = method.invoke(obj, call.getParams());
	        call.setResult(result);
        } catch (Exception e) {
	        e.printStackTrace();
        }
		return call;
	}
	
	public static void main(String[] args)throws Exception{
		SimpleServer server = new SimpleServer();
		server.service();
	}
}

// remote.service.HelloService.java
package remote.service;

import java.util.Date;

/**
 *@date 2010-3-13 下午04:29:29
 *@author dycc
 */
public interface HelloService {
	public String echo(String msg);
	public Date getTime();
}

// remote.service.HelloServiceImpl.java
package remote.service;

import java.util.Date;

/**
 *@date 2010-3-13 下午04:30:44
 *@author dycc
 */
public class HelloServiceImpl implements HelloService{
	public String echo(String msg) {
	    return "echo:" + msg;
	}
	public Date getTime() {
	    return new Date();
	}
}

// share.call.Call.java
package share.call;

import java.io.Serializable;

/**
 *@date 2010-3-13 下午04:32:04
 *@author dycc
 */
public class Call implements Serializable{
	/**
     * 
     */
    private static final long serialVersionUID = 1L;
	private String className;
	private String methodName;
	@SuppressWarnings(value="unchecked")
	private Class[] paramTypes;
	private Object[] params;
	private Object result;
	
	public Call(){
		
	}
	@SuppressWarnings(value="unchecked")
	public Call(String className,String methodName,
			Class[] paramTypes,Object[] params){
		this.className = className;
		this.methodName = methodName;
		this.paramTypes = paramTypes;
		this.params = params;
	}
	public String getClassName() {
    	return className;
    }
	public void setClassName(String className) {
    	this.className = className;
    }
	public String getMethodName() {
    	return methodName;
    }
	public void setMethodName(String methodName) {
    	this.methodName = methodName;
    }
	@SuppressWarnings(value="unchecked")
	public Class[] getParamTypes() {
    	return paramTypes;
    }
	@SuppressWarnings(value="unchecked")
	public void setParamTypes(Class[] paramTypes) {
    	this.paramTypes = paramTypes;
    }
	public Object[] getParams() {
    	return params;
    }
	public void setParams(Object[] params) {
    	this.params = params;
    }
	public Object getResult() {
    	return result;
    }
	public void setResult(Object result) {
    	this.result = result;
    }
	public String toString(){
		StringBuffer sb = new StringBuffer();
		sb.append("{className=" + className);
		sb.append(",methodName=" + methodName);
		sb.append(",result=" + result);
		sb.append("}");
		return sb.toString();
	}
}

// locale.client.SimpleClient.java
package locale.client;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import share.call.Call;

/**
 *@date 2010-3-13 下午04:58:48
 *@author dycc
 */
public class SimpleClient {
	private ObjectInputStream in;
	private ObjectOutputStream out;
	
	public void invoke(){
		try{
    		Socket socket = new Socket("localhost",8002);
    		out = new ObjectOutputStream(socket.getOutputStream());
    		Call call = new Call("remote.service.HelloServiceImpl",
    				"getTime",new Class[]{},new Object[]{});
    		out.writeObject(call);
    		out.flush();
    		// ObjectInputStream 会发生阻塞!!
    		in = new ObjectInputStream(socket.getInputStream());
    		call = (Call)in.readObject();
    		System.out.println("result=" + call.getResult());
		} catch(Exception e){
			e.printStackTrace();
		} finally{
			try{
				if(in != null){
					in.close();
				}
				if(out != null){
					out.close();
				}
			} catch(Exception e){
			}
		}
	}
	
	public static void main(String[] args){
		SimpleClient client = new SimpleClient();
		client.invoke();
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics