-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRpcServerHandler.java
More file actions
77 lines (66 loc) · 2.34 KB
/
Copy pathRpcServerHandler.java
File metadata and controls
77 lines (66 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package server;
import message.RpcRequest;
import message.RpcResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;
public class RpcServerHandler implements Runnable {
private Socket clientSocket;
private Map<String,Object> services;
public RpcServerHandler(Socket client, Map<String, Object> services) {
this.clientSocket = client;
this.services = services;
}
@Override
public void run() {
ObjectInputStream oin = null;
ObjectOutputStream oout = null;
RpcResponse response = new RpcResponse();
try {
// 1. 获取流以待操作
oin = new ObjectInputStream(clientSocket.getInputStream());
oout = new ObjectOutputStream(clientSocket.getOutputStream());
// 2. 从网络IO输入流中请求数据,强转参数类型
Object requestObj = oin.readObject();
RpcRequest request = null;
//3.处理请求
if(!(requestObj instanceof RpcRequest)){
response.setError(new Exception("请求参数错误"));
oout.writeObject(response);
oout.flush();
return;
}else{
request = (RpcRequest) requestObj;
}
//4.查找并执行服务方法
Object service = services.get(request.getClassName());
Class<?> serviceClass = service.getClass();
Method method = serviceClass.getMethod(request.getMethodName(), request.getParamTypes());
Object res = method.invoke(service, request.getParams());
response.setResult(res);
oout.writeObject(response);
oout.flush();
} catch (Exception e) {
try { //异常处理
if(oout != null){
response.setError(e);
oout.writeObject(response);
oout.flush();
}
} catch (Exception e1) {
e1.printStackTrace();
}
return;
} finally {
try {
oin.close();
oout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}