In the previous section, we did some web-related knowledge and review for implementing the Tomjetty server. Then from this section officially began to realize the Tomjetty server "cottage" tour. In order to implement a server, the first step is to build the server and be able to run properly in order to wait for requests from the client. With this in mind, we'll deal with the creation and start-up of the Tomjetty server in this section.
First, the server establishment
1. Create a new Java project called Tomjetty.
2. Under the Engineering root directory, create a new Tomjetty.config file to provide server configuration parameters.
tomjetty.port=9527
Tomjetty.requestheader.class=cn.lynn.tomjetty.requestheaderparserimpl
3. Write a tool class Tomjettyutil for the program to read server configuration parameter values.
Package cn.lynn.tomjetty;
Import java.io.IOException;
Import Java.io.FileInputStream;
Import java.util.Properties;
public class Tomjettyutil {
private static properties props = new properties ();
static {
try {
props.load (new FileInputStream (".//tomjetty.config"));
\ catch (IOException e) {
E.printstacktrace ();
System.exit (0);
}
}
public static string GetValue (String key) {return
props.getproperty (key);
}
}
4. Write a Tomjetty class that inherits from the thread class and is used to encapsulate server objects.
public class Tomjetty extends Thread {
private static serversocket server;
private socket socket;
Public Tomjetty (socket socket) {
this.socket = socket;
}
...
}
5. Provide the OpenServer () and CloseServer () methods for the Tomjetty class to encapsulate the details of opening and shutting down the server.
public static void OpenServer () throws Exception {
Server = new ServerSocket (Integer.parseint (tomjettyutil.getvalue ("Tomjetty.port"));
while (true) {
new Tomjetty (Server.accept ()). Start ();
public static void CloseServer () throws Exception {
if (server!= null) {
if (!server.isclosed ()) {
Server.clo Se ();}}}
Up to this point, the Tomjetty server has been established, and the OpenServer () and CloseServer () methods are available for external program calls to perform the operation of opening and shutting down the server.