blob: 1c93a056eba6fbe8d068cacb8b16d50a16e7af85 (
plain)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
package com.orbekk.protobuf;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
public class ConnectionHandler {
private final Socket connection;
private final BlockingQueue<Data.Response> dispatcherOutput;
private final RequestDispatcher dispatcher;
private class IncomingHandler implements Runnable {
@Override public void run() {
dispatcher.start();
while (!connection.isClosed()) {
try {
Data.Request r = Data.Request.parseDelimitedFrom(
connection.getInputStream());
if (r == null) {
tryCloseConnection();
} else {
try {
dispatcher.handleRequest(r);
} catch (InterruptedException e) {
tryCloseConnection();
return;
}
}
} catch (IOException e) {
tryCloseConnection();
}
}
dispatcher.interrupt();
}
}
private class OutgoingHandler implements Runnable {
@Override public void run() {
while (!connection.isClosed()) {
try {
Data.Response response = dispatcherOutput.take();
try {
response.writeDelimitedTo(connection.getOutputStream());
} catch (IOException e) {
tryCloseConnection();
}
} catch (InterruptedException e) {
tryCloseConnection();
}
}
dispatcher.interrupt();
}
}
public static ConnectionHandler create(Socket connection,
ExecutorService requestPool, ServiceHolder services) {
BlockingQueue<Data.Response> dispatcherOutput =
new ArrayBlockingQueue(RequestDispatcher.DEFAULT_QUEUE_SIZE);
RequestDispatcher dispatcher = new RequestDispatcher(
requestPool, dispatcherOutput, services);
return new ConnectionHandler(connection, dispatcherOutput,
dispatcher);
}
ConnectionHandler(Socket connection,
BlockingQueue<Data.Response> dispatcherOutput,
RequestDispatcher dispatcher) {
this.connection = connection;
this.dispatcherOutput = dispatcherOutput;
this.dispatcher = dispatcher;
}
public void closeConnection() {
tryCloseConnection();
}
private void tryCloseConnection() {
try {
connection.close();
} catch (IOException e) {
// Assume connection is closed.
}
}
public Runnable createIncomingHandler() {
return new IncomingHandler();
}
public Runnable createOutgoingHandler() {
return new OutgoingHandler();
}
}
|