大家好,本人目前在学习java。有一份作业要求实现一个简单的server,并能加载业务逻辑,具有可配置性。
本人关于这点的认识停留在。net程序中利用类继承和反射来达到动态加载业务逻辑,不知在java中是如何实现。
请各位大侠帮忙指点:)付spec(目前主要是第一点有困惑):
a. business logic has to be extendable. business logic can be
grouped into modules, and modules can be plugable.
b. depends on the protocol definition, the request from client has
to be able to be dispatched into the right handler.
c. depends on the protocol's style. If it is ephemeral connection
based, state has to be able to maintain between each request.
d. app server has to support multiple concurrent clients.
本人关于这点的认识停留在。net程序中利用类继承和反射来达到动态加载业务逻辑,不知在java中是如何实现。
请各位大侠帮忙指点:)付spec(目前主要是第一点有困惑):
a. business logic has to be extendable. business logic can be
grouped into modules, and modules can be plugable.
b. depends on the protocol definition, the request from client has
to be able to be dispatched into the right handler.
c. depends on the protocol's style. If it is ephemeral connection
based, state has to be able to maintain between each request.
d. app server has to support multiple concurrent clients.
你需要自己设计模块的统一入口,好让每一个具体的模块有一个实现的规范,从而能够动态插入。可以参照一个JPF,这是一个开源的项目,就是一个插件框架。
也许楼主是高手也不一定!!!
Properties。
不知道LZ的Server是什么级别的,如果是从底层开始,即main方法入口,那LZ还要懂得解析协议
比如从socket获得数据后,定义一个Engine或Analyzer类对数据解析,
分析出是什么请求协议,比如FTP或HTTP,然后把所有信息都封装到Context或Request中
然后把这些信息再传给一个处理器Processor,Processor调用一些Validater或Filter等进行验证过滤,然后根据不同的请求调用Dispatcher
等等等等,一步一步从下层往上传,直到传到业务处理层
太复杂的就不多数说,毕竟只是作业,只是想让LZ掌握动态加载业务逻辑
其实很简单,首先定义一个接口或抽象类,所有业务逻辑类都实现这个接口或继承这个抽象类
然后把业务逻辑都定义在配置文件里,property或xml文件都可以
比如对于property文件xxxlogic=xxxpakege.xxxclass,xml可以定义<logic id="xxxlogic" class="xxxpackege.xxxclass"/>等
然后再请求数据中取出逻辑业务的参数,比如业务逻辑id=xxxlogic,params=yyyy等等
然后在配置文件中查找该参数对应的class,即找到xxxpackege.xxxclass
然后通过反射xxxlogicInterface xxx = Class.forName("xxxpackege.xxxclass").newInstance(paramX); //如果构造函数需要参数的话
然后再调用接口的方法xxx.xxxMethod(params);
大概就这么一个原理了
过于这个作业,其实只是一家公司给我布置得,目的可能是让我有目的学习java而已。目前我写的代码(简单实现协议和SESSION)如下,也请大家帮我指点下:
myclient
-Client.java
myexception
-ArgumentException.java
myserver
-Server.java
-Session.java
Protect
-Request.java
-Response.java
---------
package Protect;import MyException.ArgumentException;public class Request {
private String action = null;// 动作 private java.util.UUID sessionID = null;// private String info = null;// 具体业务信息 /**
* 构造函数,用接受的request构造V1对象,可通过属性获取具体的信息
*
* @param protectString
* @throws ArgumentException
*/
public Request(String protectString) throws ArgumentException {
int index1 = protectString.indexOf("|");
if (index1 < 0||index1==protectString.length())
throw new ArgumentException("构造失败");
int index2 = protectString.indexOf("|", index1+1);
if (index2 < 0)
throw new ArgumentException("构造失败"); action = protectString.substring(0, index1);
String strSessionID = protectString.substring(index1 + 1, index2);
sessionID = (strSessionID.equals("") ? null : java.util.UUID
.fromString(strSessionID));
info = protectString.substring(index2 + 1);
} /**
* 用属性设置V1对象后,通过该方法获取Request文本
*
* @return
* @throws ArgumentException
*/
public static String GetProtectString(String action,
java.util.UUID sessionID, String info) throws ArgumentException {
if (action == null || info == null)
throw new ArgumentException("构造失败"); if (action.indexOf("|") > 0)
throw new ArgumentException("参数Action不能包含'|'符号"); if (info.indexOf("|") > 0)
throw new ArgumentException("参数Info不能包含'|'符号"); return action + "|" + (sessionID == null ? "" : sessionID.toString())
+ "|" + info;
} public String getAction() {
return action;
} public String getInfo() {
return info;
} public java.util.UUID getSessionID() {
return sessionID;
}
}
----------------------
package Protect;
import MyException.ArgumentException;
public class Response {
private String meta = null;// private java.util.UUID sessionID = null;// private String info = null;// 具体业务信息 public Response(String responseString) throws ArgumentException {
int index1 = responseString.indexOf("|");
if (index1 < 0||index1==responseString.length())
throw new ArgumentException("构造失败");
int index2 = responseString.indexOf("|", index1+1);
if (index2 < 0)
throw new ArgumentException("构造失败"); meta = responseString.substring(0, index1);
String strSessionID = responseString.substring(index1 + 1, index2);
sessionID = (strSessionID.equals("") ? null : java.util.UUID
.fromString(strSessionID));
info = responseString.substring(index2 + 1);
} public static String GetProtectString(String meta,
java.util.UUID sessionID, String info) throws ArgumentException {
if (meta == null || info == null)
throw new ArgumentException("构造失败"); if (meta.indexOf("|") > 0)
throw new ArgumentException("参数Action不能包含'|'符号"); if (info.indexOf("|") > 0)
throw new ArgumentException("参数Info不能包含'|'符号"); return meta + "|" + (sessionID == null ? "" : sessionID.toString())
+ "|" + info;
} public String getMeta() {
return meta;
} public String getInfo() {
return info;
} public java.util.UUID getSessionID() {
return sessionID;
}
}
//-------------------------
package Protect;
import MyException.*;
public class Response {
private String meta = null;// private java.util.UUID sessionID = null;// private String info = null;// 具体业务信息 public Response(String responseString) throws ArgumentException {
int index1 = responseString.indexOf("|");
if (index1 < 0||index1==responseString.length())
throw new ArgumentException("构造失败");
int index2 = responseString.indexOf("|", index1+1);
if (index2 < 0)
throw new ArgumentException("构造失败"); meta = responseString.substring(0, index1);
String strSessionID = responseString.substring(index1 + 1, index2);
sessionID = (strSessionID.equals("") ? null : java.util.UUID
.fromString(strSessionID));
info = responseString.substring(index2 + 1);
} public static String GetProtectString(String meta,
java.util.UUID sessionID, String info) throws ArgumentException {
if (meta == null || info == null)
throw new ArgumentException("构造失败"); if (meta.indexOf("|") > 0)
throw new ArgumentException("参数Action不能包含'|'符号"); if (info.indexOf("|") > 0)
throw new ArgumentException("参数Info不能包含'|'符号"); return meta + "|" + (sessionID == null ? "" : sessionID.toString())
+ "|" + info;
} public String getMeta() {
return meta;
} public String getInfo() {
return info;
} public java.util.UUID getSessionID() {
return sessionID;
}
}
//ArgumentException.java
//-------------------------
package MyException;public class ArgumentException extends Exception{
public ArgumentException(){
super();
}
public ArgumentException(String msg){
super(msg);
}
public ArgumentException(String msg,Throwable cause){
super(msg,cause);
}
public ArgumentException(Throwable cause){
super(cause);
}
}
//Client.java
//-----------------
package MyClient;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;import MyException.*;
import Protect.*;public class Client {
private String host = "localhost"; private int port = 8205; private Socket socket = null; private java.util.UUID sessionID = null; private String action = null; private String info = null; public Client() {
} // 循环向服务器发送请求并处理应答
public void receive_send() {
BufferedReader line = new BufferedReader(new InputStreamReader(
System.in));
try {
while (true) {
System.out.println("-------------------------");
System.out.println("my sessionid is:"
+ (sessionID == null ? "no sessionid" : sessionID
.toString()));
try {
socket = new Socket(host, port);
} catch (IOException e) {
e.printStackTrace();
} BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(),
true); System.out.println("please input the action:");
action = line.readLine(); System.out.println("please input the info:");
info = line.readLine(); try {
String strRequest = Request.GetProtectString(action,
sessionID, info);
out.println(strRequest); String strResponse = in.readLine(); this.sessionID = new Response(strResponse).getSessionID(); System.out.println("[from server]:" + strResponse); } catch (ArgumentException e) {
System.out.println(e.getMessage());
continue;
} finally {
out.close();
in.close();
}
} } catch (IOException e) {
e.printStackTrace();
} finally {
try {
line.close();
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) {
Client client = new Client();
client.receive_send();
}
}
//Server.java
//--------------
package MyServer;import java.net.*;
import java.io.*;
import java.util.*;import MyException.*;
import Protect.*;public class Server {
private int port = 8205;// 服务器端口 private int backlog = 16;// 并发连接数 private ServerSocket serverSocket = null; public Server() {
try {
serverSocket = new ServerSocket(port, backlog);
} catch (IOException e) {
e.printStackTrace();
}
} public void Service() {
while (true) {
Socket socket = null;
try {
socket = this.serverSocket.accept();
Thread transfersDataThread = new Thread(new DataHandler(socket));// 每收到一个请求,启动一个线程进行处理
transfersDataThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) {
System.out.println("Server begin");
Server sss = new Server();
sss.Service();
}
}class DataHandler implements Runnable {
private Socket socket; private java.util.UUID sessionID = null; public DataHandler(Socket socket) {
this.socket = socket;
} public void run() {
try {
System.out.println("Connect Client" + socket.getInetAddress() + ":"
+ socket.getPort()); BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); String line = in.readLine(); Request protect = new Request(line); System.out.println("recive info:" + line); // 处理未初始化的SESSION
if (protect.getSessionID() == null)
sessionID = java.util.UUID.randomUUID();
else
sessionID = protect.getSessionID(); // 根据请求的Action加载相应模块处理
String action = protect.getAction().toLowerCase();
if (action.equals("get"))
out.println( new ActionGet(protect.getInfo(), sessionID).GetResponse());
else
out.println(Response.GetProtectString("info", sessionID, "没有找到处理该动作的MODEL(目前只处理GET请求)")); out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ArgumentException e) {
System.out.println(e.getMessage());
} finally {
try {
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}// 处理GET请求的类
class ActionGet {
private String info = null; private java.util.UUID sessionID = null;
private Session session = null; public ActionGet(String info, java.util.UUID sessionID) {
this.info = info;
this.sessionID = sessionID;
session = Session.GetSession(sessionID); } public String GetResponse() {
String response = null;
try {
response = Response.GetProtectString("info", session.sessionID,
"do sth with the request '" + info + "',last visit time is:"+session.get("lastTime"));
} catch (ArgumentException e) {
System.out.println(e.getMessage());
}
session.put("lastTime", Calendar.getInstance().getTime());
return response;
}
}
//Session.java
//-------------------
package MyServer;import java.util.*;public class Session extends Hashtable { public java.util.UUID sessionID = null; private static Hashtable allSessions = new Hashtable(); private Session() { } public static Session GetSession(java.util.UUID sessionID) {
if (!allSessions.containsKey(sessionID)) {
Session session = new Session();
session.sessionID = sessionID;
allSessions.put(sessionID, session);
}
return (Session) allSessions.get(sessionID);
}
}