📄 handler.java
字号:
import java.io.*;
import java.net.*;
import java.util.*;
/**
* 这个类是socket连接的处理器
* 例如:
* <pre>
* Handler aHandler = new Handler(clientSocket, myMusicDataAccessor);
* aHandler.start();
* </pre>
*
*
*/
public class Handler extends Thread implements StoneForestProtocol {
protected Socket clientSocket;
protected ObjectOutputStream outputToClient;
protected ObjectInputStream inputFromClient;
protected MusicDataAccessor myMusicDataAccessor;
protected boolean done;
public Handler(Socket theClientSocket, MusicDataAccessor theMusicDataAccessor) throws IOException {
clientSocket = theClientSocket;
outputToClient = new ObjectOutputStream(clientSocket.getOutputStream());
inputFromClient = new ObjectInputStream(clientSocket.getInputStream());
myMusicDataAccessor = theMusicDataAccessor;
done = false;
}
public void run() {
try {
while (!done) {
log("等待命令...");
int opCode = inputFromClient.readInt();
log("opCode = " + opCode);
switch(opCode) {
case StoneForestProtocol.OP_GET_MUSIC_CATEGORIES:
opGetMusicCategories();
break;
case StoneForestProtocol.OP_GET_MUSIC_RECORDINGS:
opGetMusicRecordings();
break;
default:
System.out.println("错误代码");
}
}
}
catch (IOException exc) {
log(exc);
}
}
protected void opGetMusicCategories() {
try {
ArrayList categoryList = myMusicDataAccessor.getCategories();
outputToClient.writeObject(categoryList);
outputToClient.flush();
log("发出 " + categoryList.size() + " 类别信息到客户端到客户端.");
}
catch (IOException exc) {
log("发生异常: " + exc);
}
}
protected void opGetMusicRecordings() {
try {
log("读取份类信息");
String category = (String) inputFromClient.readObject();
log("类别是 " + category);
ArrayList recordingList = myMusicDataAccessor.getRecordings(category);
outputToClient.writeObject(recordingList);
outputToClient.flush();
log("发出 " + recordingList.size() + " CD信息到客户端.");
}
catch (IOException exc) {
log("发生异常: " + exc);
exc.printStackTrace();
}
catch (ClassNotFoundException exc) {
log("发生异常: " + exc);
exc.printStackTrace();
}
}
public void setDone(boolean flag) {
done = flag;
}
protected void log(Object msg) {
System.out.println("处理器: " + msg);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -