版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lwl2014100338/article/details/81900912
服务接口
package com.lwl.rpc.tcp;
public interface SayHelloService {
/**
*
*/
public String sayHello(String helloArg);
}
服务实现
package com.lwl.rpc.tcp;
/**
* @author zzjs
* @ClassName: SayHelloServiceImpl
* @Description: TODO
* @Date 2018-08-19 19:10
* @Version 1.0
**/
public class SayHelloServiceImpl implements SayHelloService {
@Override
public String sayHello(String helloArg) {
if (helloArg.equals("hello")) {
return "hello";
} else {
return "bye bye";
}
}
}
服务提供者
package com.lwl.rpc.tcp;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
/**
* @author liuweilong
* @ClassName: Provider
* @Description: 服务提供者
* @Date 2018-08-20 21:26
* @Version 1.0
**/
public class Provider {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ServerSocket server=new ServerSocket(1234);
while (true){
Socket socket=server.accept();
//读取服务消息
ObjectInputStream input= new ObjectInputStream(socket.getInputStream());
String interfacename= input.readUTF();
String methodName= input.readUTF();
Class<?>[] parameterTypes=(Class<?>[])input.readObject();
Object [] arguments= (Object[]) input.readObject();
//执行调用
Class serviceinterfaceclass= Class.forName(interfacename);//得到接口clss
//服务端事先将服务实例化好放入Map
HashMap services=new HashMap();
Object service= services.get(interfacename);//得到服务实现对象
Method method= serviceinterfaceclass.getMethod(methodName,parameterTypes);//取得要调用的方法
Object result= method.invoke(service,arguments);
ObjectOutputStream output= new ObjectOutputStream(socket.getOutputStream());
output.writeObject(result);
}
}
}
服务消费者
package com.lwl.rpc.tcp;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
/**
* @author liuweilong
* @ClassName: Consumer
* @Description: 服务消费者
* @Date 2018-08-20 21:15
* @Version 1.0
**/
public class Consumer {
public static void main(String[] args) throws NoSuchMethodException, IOException, ClassNotFoundException {
String interfacename= SayHelloService.class.getName();
Method method= SayHelloService.class.getMethod("sayHello", String.class);
Object [] arguments={"hello"};
Socket socket=new Socket("127.0.0.1",1234);
//方法名和参数传递到远端
ObjectOutputStream output= new ObjectOutputStream(socket.getOutputStream());
output.writeUTF(interfacename);
output.writeUTF(method.getName());
output.writeObject(method.getParameterTypes());
output.writeObject(arguments);
//远端读取方法执行结果
ObjectInputStream input= new ObjectInputStream(socket.getInputStream());
Object result= input.readObject();
}
}