客户端:
package cn.itcast_04_reflect.socket; import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket; public class TestClient {
public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 9898);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream(); PrintWriter pw = new PrintWriter(new BufferedOutputStream(out));
pw.println("cn.itcast_04_reflect.rpc.TestBusiness:getPrice:yifu");
pw.flush(); BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine = br.readLine(); System.out.println("client get result: " + readLine); socket.close();
}
}
package cn.itcast_04_reflect.socket; import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket; public class TestServerTask implements Runnable{
private Socket socket;
public TestServerTask(Socket socket){
this.socket = socket;
} @Override
public void run() {
InputStream in;
OutputStream out;
try {
in = socket.getInputStream();
out = socket.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in));//一次读一行,客户端的消息要带回车符。
String request=null;
while((request = br.readLine())!=null) {
request = br.readLine();
}
String[] split = request.split(":");
String className = split[0];
String methodName = split[1];
String methodParam= split[2]; Class<?> forName = Class.forName(className);
System.out.println("calling class: " + forName);
Object newInstance = forName.newInstance();
Method method = forName.getMethod(methodName,String.class);
System.out.println("calling method: " + method);
Object invoke = method.invoke(newInstance, methodParam);
System.out.println("results: " + (int)invoke); PrintWriter pw = new PrintWriter(new BufferedOutputStream(out));
pw.println((int)invoke);
pw.flush(); br.close();
pw.close();
socket.close(); } catch (Exception e) { e.printStackTrace();
} } public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket();
server.bind(new InetSocketAddress("localhost",9898));
while(true){
Socket socket = server.accept();
new Thread(new TestServerTask(socket)).start();
}
}
} public interface IBusiness {
public int getPrice(String good);
} public class TestBusiness implements IBusiness{
@Override
public int getPrice(String good){
return good.equals("yifu")?10:20;
}
}