导语
重定向器是特殊用途的HTTP服务器的另一个简单而有用的应用程序。它的作用就是将用户从一个WEB网站重定向到另外一个网站。下面是一个简单的例子,程序沿用上一个SingleHttpServer代码。看起来很容易读懂。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
public class Redirector {
private static final Logger logger = Logger.getLogger("Redirector");
private final int port;
public Redirector(int _port) {
try {
Handler handler = new FileHandler("redirector.log");
logger.addHandler(handler);
} catch (SecurityException | IOException e) {
throw new RuntimeException("无法记录日志");
}
port = _port;
}
public void start() {
try (ServerSocket server = new ServerSocket(port)) {
logger.info("Redirecting connections on port " + server.getLocalPort() + "to www.xdysite.cn/index.html" );
while (true) {
try {
Socket socket = server.accept();
Thread t = new RedirectThread(socket);
t.start();
} catch (IOException e) {
logger.warning("Exception accepting connection");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Redirector redirector = new Redirector(8080);
redirector.start();
}
}
class RedirectThread extends Thread{
private final Socket socket;
private static final String header;
private static final String body;
static {
header = "HTTP/1.1 302 Found
"
+ "Server: Redirector 1.1
"
+ "Location: http://www.xdysite.cn/index.html
"
+ "Content-Type: text/html
";
body = "<html><head><title>文件已移到别处</title></head><body><bold>文件已移到别处</bold></body></html>";
}
public RedirectThread(Socket _socket) {
socket = _socket;
}
@Override
public void run() {
try(
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
) {
String get = reader.readLine();
if (get != null && get.indexOf("HTTP") != -1) {
writer.write(header + "Date: " + new Date() + "
");
writer.write(body);
writer.flush();
}
} catch (IOException e) {
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}