Network Service
Web Services ,Distributed Objects etc
most have same basic structure;
- Read Request
- Decode Rquest
- Process Service
- Encode Reply
- Send Reply
当今网络上的各种基于TCP/IP的应用服务,请求,响应的处理过程的本质流程结构均为
- 从底层IO读取字节请求
- 把读取后的字节请求进行解码成为自己的业务请求对象
- 把解码后的业务请求对象进行业务处理
- 把处理后的响应编码为底层IO可写入的字节响应
- 利用底层IO返回(发出)编码后的字节响应
But Differ in cost nature performance of each step: Xml Parsing,Json Parsing,File transfer,Web page generation,Computational Service
每步骤所使用到的一些技术手段不一样:例如解码协议是自定义的还是使用业界流行的?是文本协议还是二进制协议?处理过程就结合具体业务进行处理等
Classic Service Designs 经典的服务模式
class Server implements Runnable {
public void run() {
try {
ServerSocket ss = new ServerSocket(PORT);
while (!Thread.interrupted())
new Thread(new Handler(ss.accept())).start();
// or, single-threaded, or a thread pool
} catch (IOException ex) { /* ... */ }
}
static class Handler implements Runnable {
final Socket socket;
Handler(Socket s) { socket = s; }
public void run() {
try {
byte[] input = new byte[MAX_INPUT];
socket.getInputStream().read(input);
byte[] output = process(input);
socket.getOutputStream().write(output);
} catch (IOException ex) { /* ... */ }
}
private byte[] process(byte[] cmd) { /* ... */ }
}
}
Each Handler May Be Start in its own Thread
Advantage: