本篇主要完成服务端,字节流接收与发送,请求解析,响应参数编码。
1.请求解析
public class NetMessage {
private int action;
private String param;
public NetMessage(String request) {
String[] split = request.split("&&");
this.action = Integer.parseInt(split[0]);
this.param = split[1];
}
}
请求参数事例:方法哈希值&&请求参数字符串
2. 侦听客户端请求
protected abstract void dealRequest(NetMessage netMessage);
@Override
public void run() {
DataInputStream dataInputStream = null;
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dealRequest(new NetMessage(dataInputStream.readUTF()));
} catch (IOException ignored) {
}
close(null,dataInputStream,null);
}
这里使用了线程,希望能够及时处理客户端消息。首先建立输入流,接收到请求,并解析,交由具体处理器处理。
3.消息响应
protected void response(String message) {
try {
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(message);
close(dataOutputStream, null, socket);
} catch (IOException e) {
e.printStackTrace();
}
}
当方法调用结束后,将处理结果以字符串形成回应。完成响应后,就需要关闭通信。
4.资源回收
public static void close(DataOutputStream dataOutputStream,DataInputStream dataInputStream ,Socket socket) {
try {
if (dataOutputStream != null) {
dataOutputStream.close();
}
} catch (IOException ignored) {
}
try {
if (dataInputStream != null) {
dataInputStream.close();
}
} catch (IOException ignored) {
}
try {
if (socket != null) {
socket.close();
}
} catch (IOException ignored) {
}
}