這是使用Java的序列化機制的絕佳機會。你可以這樣做(假設你捕獲所有異常有關,這是爲了簡明扼要省略)
class ClientListeningThread {
ObjectInputStream in;
ObjectOutputStream out;
ClientListeningThread(Socket s) {
in = new ObjectInputStream(s.getInputStream());
out = new ObjectOutputStream(s.getOututStream());
}
public void run() {
while(true) {
ClientMessage message = (ClientMessage)in.readObject();
engine.addMessage(this,message); // add to the message queue, signifiying which listening thread to give the response to
}
}
public void send(ServerMessage message) {
out.writeObject(message);
}
}
您的郵件甚至可以在它們回調
類LoginMessage {
public final String username;
public final String password;
public LoginMessage(String username, String password) {
this.username = username;
this.password = password;
}
public void callback(ClientListeningThread thread, ServerProcessor engine) {
ServerMessage response = engine.attemptLogin(username,password);
thread.send(response);
}
}
而在你的發動機
while(!requests.isEmpty()) {
ClientRequest request = requests.poll();
ClientListeningThread = request.thread;
ClientMessage message = request.message;
request.callback(thread,this);
}
看不到序列化在這裏發揮作用。另請參閱我的編輯。不管怎麼說,還是要謝謝你。 – 2011-04-30 18:06:02