📄 httpserver.secure
字号:
package com.wrox.httpserver;
import java.io.*;
import java.net.*;
import java.util.*;
import java.security.KeyStore;
import javax.net.*;
import javax.net.ssl.*;
import javax.security.cert.X509Certificate;
/**
* The HTTPServer main application. It starts the server as a user
* thread and presents a console to allow graceful shutdown.
*/
public class HTTPServer extends HTTPConstants implements Runnable {
// Localized messages and the application itself
private static HTTPLocalizedResources resources;
// Check if we run with the right VM and read resources
static {
String vers = System.getProperty("java.version");
if (vers.compareTo("1.3.0") < 0)
{
System.err.println(VMVERSION_ERROR);
// Exit the VM
System.exit(1);
}
try
{
// Load locale-specific messages
resources = new HTTPLocalizedResources("msg.httpserver");
}
catch (MissingResourceException mre)
{
System.err.println(RESOURCE_ERROR);
System.exit(1);
}
}
/**
* Constructs an HTTPServer object, checks the parameters and constructs the
* utility and configuration objects.
*/
public HTTPServer(String[] args)
{
// Check if the correct application parameters have been provided, we
// expect the name of the properties file
if (args != null && args.length == 1)
{
try
{
HTTPConfig.initializeConfig(args[0]);
}
catch (ConfigFileException e)
{
// An error occurred while reading the information
// A locale-specific error message is retrieved and displayed
System.err.println(
resources.getResourceString("ERROR_HTTP_CONFIG") + e.getMessage());
exit(ABNORMAL_TERMINATION);
}
}
else
{
// Write usage information and terminate
System.err.println(resources.getResourceString("ERROR_INVALID_ARGUMENT"));
exit(ABNORMAL_TERMINATION);
}
// Initialize MIME converter
try
{
MimeConverter.initializeConverter(MIME_TYPES_FILES);
}
catch (ConfigFileException e)
{
// An error occurred while reading the mime types
System.err.println(
resources.getResourceString("ERROR_MIME_CONFIG") + e.getMessage());
exit(ABNORMAL_TERMINATION);
}
// The configuration has been read, now we can initialize the logger
try
{
HTTPLog.initializeLogger(HTTPConfig.config.getLogfile());
}
catch (IOException e)
{
// An error occurred while reading the mime types
System.err.println(
resources.getResourceString("ERROR_OPEN_LOGFILE") + e.getMessage());
exit(ABNORMAL_TERMINATION);
}
}
/**
* Exits the VM with a success return code.
*/
private void exit()
{
exit(NORMAL_TERMINATION);
}
/**
* Exits the VM with a specified exit code.
*/
private void exit(int status)
{
System.exit(status);
}
/**
* Starts the application, creates the HTTPServer and starts it as a thread
* and executes the server console.
*/
public static void main(String[] args)
{
// Create an application instance
HTTPServer theApp = new HTTPServer(args);
// Start the server
Thread server = new Thread(theApp);
server.setDaemon(true);
server.start();
// Display console to allow the user to gracefully shut down the server
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw =
new BufferedWriter(new OutputStreamWriter(System.out));
while (true)
{
try
{
bw.write(resources.getResourceString("CONSOLE_PROMPT"));
bw.flush();
String input = br.readLine();
if (input != null
&& input.compareToIgnoreCase(
resources.getResourceString("CONSOLE_QUIT_COMMAND"))
== 0)
{
// The user requests to shut down the server
theApp.shutdown();
theApp.exit();
}
}
catch (Exception e)
{
// Shutdown when a console exception occurs
theApp.shutdown();
theApp.exit(ABNORMAL_TERMINATION);
}
}
}
/**
* Returns a server socket factory for either secure or non-secure connections.
*/
private ServerSocketFactory getServerSocketFactory(boolean secure)
{
if (secure)
{
SSLServerSocketFactory ssf = null;
try
{
// Set up a key manager to do server authentication
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks;
char[] passphrase = "passphrase".toCharArray();
ctx = SSLContext.getInstance("TLS");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("testkeys"), passphrase);
kmf.init(ks, passphrase);
ctx.init(kmf.getKeyManagers(), null, null);
ssf = ctx.getServerSocketFactory();
return ssf;
}
catch (Exception e)
{
// Ignore the exception and return null
return null;
}
}
else
return ServerSocketFactory.getDefault();
}
/**
* Runs the server.
*/
public void run()
{
ServerSocket server = null;
try
{
// Get port to listen at for incoming requests
int port = HTTPConfig.config.getPort();
// Create socket and listen for incoming connections
// Request a server socket factory that constructs secure sockets
ServerSocketFactory ssf = getServerSocketFactory(true);
if (HTTPConfig.config.getBindAddress() == null)
{
server = ssf.createServerSocket(port);
}
else
server = ssf.createServerSocket(port, DEFAULT_BACKLOG,
HTTPConfig.config.getBindAddress());
// Set an infinite timeout
server.setSoTimeout(0);
while (true)
{
Socket socket = server.accept();
Thread request = new Thread(new HTTPRequest(socket));
request.setDaemon(true);
request.start();
}
}
catch (Exception e)
{
System.err.println(
resources.getResourceString("ERROR_HTTP_SERVER") + e.getMessage());
exit(ABNORMAL_TERMINATION);
}
finally
{
try
{
if (server != null)
server.close();
}
catch (IOException e)
{
// Ignore this exception
}
}
}
/**
* Shuts down the server.
*/
public void shutdown()
{
// Closes the log
HTTPLog.logger.close();
}
private static final int ABNORMAL_TERMINATION = 1;
private static final int DEFAULT_BACKLOG = 50;
// Class constants
private static final String MIME_TYPES_FILES = "mime";
private static final int NORMAL_TERMINATION = 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -