62 lines
No EOL
1.6 KiB
Java
62 lines
No EOL
1.6 KiB
Java
package dev.peerat.framework;
|
|
|
|
import java.net.Socket;
|
|
|
|
import dev.peerat.framework.auth.AuthException;
|
|
|
|
public class Client<U extends User> extends Thread{
|
|
|
|
private HttpReader reader;
|
|
private HttpWriter writer;
|
|
private Router<U> router;
|
|
|
|
public Client(Socket socket, Router<U> router) throws Exception{
|
|
this.reader = new HttpReader(socket);
|
|
this.writer = new HttpWriter(socket);
|
|
this.router = router;
|
|
}
|
|
|
|
@Override
|
|
public void run(){
|
|
Context context = null;
|
|
try{
|
|
String[] headers = reader.readLine().split("\\s");
|
|
reader.readHeaders();
|
|
|
|
RequestType type = RequestType.valueOf(headers[0]);
|
|
context = new Context(type, headers[1], isLogin(type, reader), writer, router.getDefaultHeaders(type));
|
|
router.exec(context, reader, writer);
|
|
writer.flush();
|
|
writer.close();
|
|
}catch(AuthException e){
|
|
this.router.getExceptionLogger().pushValue(e);
|
|
}catch(Throwable e){
|
|
this.router.getExceptionLogger().pushValue(e);
|
|
if(context != null && context.getResponseCode() == 0){
|
|
try{
|
|
context.response(500);
|
|
writer.flush();
|
|
writer.close();
|
|
}catch(Exception ex){
|
|
this.router.getExceptionLogger().pushValue(ex);
|
|
}
|
|
}
|
|
}
|
|
if(context != null) router.getLogger().pushValue(context);
|
|
}
|
|
|
|
private User isLogin(RequestType type, HttpReader reader) throws AuthException{
|
|
try{
|
|
return this.router.getUser(type, reader);
|
|
}catch(Exception e){
|
|
try{
|
|
writer.response(401, this.router.getDefaultHeaders(type));
|
|
writer.flush();
|
|
writer.close();
|
|
}catch(Exception ex){
|
|
this.router.getExceptionLogger().pushValue(ex);
|
|
}
|
|
throw new AuthException(e);
|
|
}
|
|
}
|
|
} |