How to write NT services using Java
Yangshan River
Introduction: This article explains how to quickly write secure and reliable NT services using Java features and show how Java's multi-thread implementation, and how to apply socket to implement network services.
Keywords: Java JNTSVC.EXE NT service multi-thread socket programming
I. NT service introduction
The so-called NT service is actually a class of special applications so-called NT services. It is actually a process that can be automatically started at a certain identity at a certain identity at a system startup. The FTP Server, HTTP Server, offline printing, etc. are provided in the form of NT services. This actually similar to the UNIX root daemon process. NT services are summarized, and NT services are also the following characteristics:
1. You can start from starting, do not need to be started. This is an important feature for the server. Of course, you can decide whether the service is started from start, and even shielding a service. 2, NT service does not have a user interface, basically similar to a DOS program, because the NT service must run for a long time, so you don't want to have your own interface as a normal Win32 process. But the NT service can interact with the user, which is a special service process. You can see the service process through the NT task manager. 3, NT service to manage, install, start, stop, and removal, etc. The service controller of the control panel is to use the SCM interface to manage all services in the system. In fact, there are some programs or commands that can control services, Net.exe, Server Manager, etc., SCM.exe, etc. 4, these processes run in a certain identity to facilitate access to server resources. Under normal circumstances, use Localsystem accounts in the domain, this account has complete access rights to most resources (unless special prohibited), which can ensure the "power" of the service program. However, some services use special accounts to run, you can also specifically set a service account. 5, the system is automatically run in a thread mode, in general, but more system resources, this is different from ordinary processes. If the thread mode is not used, the general process often consumes the entire CPU resource. It is generally necessary to exist, and the task that can not consume excessive resource is the most appropriate.
Second, Java preparation services
1. As a localized implementation, the Java program that implements the NT service is of course not 100% pure Java. Although the standard class library is unable to implement our designation of the NT service, the MS provides a set of SDK for Java (this article adopted It is Microsoft SDK for Java 4.0), which is mentioned how to use MS-provided extension libraries and corresponding tools to implement programs needed for Windows platforms. These include tools for achieving the desired Class library API framework for NT services and tools that assemble the Class files compiled by Java into a standard NT service program. The download path for the SDK can be found from www.microsoft.com/java/.
2 Follow the framework to achieve the details of our concern. Install Service.zip to the development machine Install Service Library to Java Extension / WinNT / Java / TrustLib, if developed under other operating systems, refer to this system directory for installation files.
3. There is also a JNTSVC.EXE file in this directory, which is the meaning of Java NT Service. She can help you assemble a standard NT service executable file that will be assembled as a standard NT service that will be implemented in compiled Class files implemented according to the SDK. JNTSVC helps us set up all NT service programs on the basis of compiled .class files, it is important tool to get NT services depends on how to effectively take advantage of her. In order to be able to call her from any other directory console window, we add the full path of the directory where Jntsvc.exe is located to the PATH environment variable. This can be set by setting the environment variable by setting the advanced property page of the system attribute. 4, follow the requirements, we write all the code, then compile the written Java program to get the class file. Of course, we will not launch her in VJ Studio, because it currently has no portions of the executable file, the system cannot start her. In order to get the NT service, we need to perform a command in the console window of the directory where the Class file is located: x:> jntsvc * .class /out :echosvc.exe / svccmain: echosvc "/ serviceename: echosvc". Specific JNTSVC parameters We can take a look at JNTSVC -? Get, herein, it is probably: assemble all Class files in the current directory into a NT service process exe file, file named echosvc.exe, service startup entry In echosvc.class, the corresponding service name in the registry is the EchosVC specified by the / serviceName parameter. If there are multiple NT services that need to be assembled in an EXE file, you can also specify each service display name after the / out parameter. / SVCMAIN parameter specifies the entry of the service, the so-called entry is to start from which class of the service startup is started. "/ ServiceName:" The parameter specifies what the service will appear in what name. These parameters are the JNTSVC.EXE utility requires the information necessary to assemble the service. According to this information, the compiled .CLASS file is required to obtain an executable according to Win32 format.
It should be noted that the operation of this EXE file must have JVM, which is actually provided by explaining .class to implement service. If additional extension packages are needed, you can specify an additional extension package at the / classpath parameter. Therefore, JVM must be present on the machine of the NT service written by Java. If you have IE5.x, then you don't have to worry about this problem, the IE core component already includes JVM; but if it is an IE6 version, you need to download JVM on the MS website. It is more convenient if you are installing SDK for Java installed on the server.
5. If there is no error, you will get an executable echosvc.exe. Like most service executables, it can install themselves into the system: echosvc.exe -install, this process will add some projects to the system registry, especially about the service, SCM can also list this Service. We can use the DOS NT service control command NET START / STOP under the console to test whether the service is really like a normal service, and it can be controlled in terms of standard mode. Of course, there will be no problem in the service manager.
Third, Echo service
When the system loads the service process, the entry is in the ECHOSVC constructor, we can see that this constructor is a parameter similar to the port main () of the same general program. Import com.ms.service. *;
Public Class Echosvc Extends Service
{Static Thread MAINSVC = NULL; // Defining Service Main Thread
Public echosvc (String [] ARGS) // Constructs this service
{
Checkpoint (1000);
Strunning (accept_shutdown | accept_pause_continue | accept_stop); // The service accepts the service control of the service control MAINSVC = New Thread () NEW mainsvcthread ());
MAINSVC.START ();
System.out.println ("The Echo Service Was Started SuccessFully!"); // Record event, you can see through the event viewer
}
}
Checkpoint is a Synchronous method of Service, indicating that the system is changing the status of the service, you need to wait for 1 second. Here we launched a thread, actually equivalent to a process, she is the main thread of the service process. In this thread we responded to the control of this service in this thread. The rough expression is:
Public Class Mainsvcthread Implements Runnable / / Implement Thread Control
{
Public static boolean stop = false; // The internal variable controlled by the system determines the startup, pause of the service process (thread).
Public static boolean pause = false;
Public void Run ()
{
While (! stop)
{
While (! Pause &&! stop)
{
. . . / / Here is the service control logic, which will be fulfilled here.
}
Try
{Thread.sleep (5000); // Temporary or stop after 5 seconds
Catch (InterruptedException E)
{}
}
Try
{Thread.sleep (1000);
Catch (InterruptedException IE)
{}
}
} // Run end
}
In the service logic control, we will implement the Echo service. Our Echo Service Listening 2002 port, receive any row of entries in the client, then add "Echo:" and return. If the client enters a quit phrase that the service thinks that this is a command to close this socket, the current socket connection is automatically turned off to stop the current connection. Specific implementation (Echothread.java code):
Public void Run ()
{
String line;
DataInputstream in;
Printwriter out;
Boolean EXITFLAG = FALSE;
Try
{
IN = New DataInputStream (So.GetinputStream ()); // Get the input stream of the socket
OUT = New Print Writer (no.getoutputstream ()));
Out.println ("You Have Connected to Echosvc!"); // Send greetings
Out.flush ();
While ((line = in.readline ())! = null) // Read
{
Line = line.trim ();
Line.Equalsignorecase ("quit"))
{
Out.println ("echo:" line);
Out.flush ();
Return;
}
Else
{
Out.println ("echo:" line);
Out.flush ();
}
}
In.Close ();
Out.close ();
}
Catch (IOEXCEPTION IOE)
{}
}
The Echo service is mainly to disappoint the character emission to the customer and add the echo: prefix to indicate the content returned from the server. If the customer enters "quit", then this is the performance of the server to stop service. How to debug NT service process works. If you call this function directly to provide the client's Echo socket service, there is no error on the logically, but you cannot support multiple users at the same time. In order to be able to provide multiple services, it allows simultaneous number of users to connect this server (this situation is not small in many network services), we can implement this logic in the thread created by MainsVCTRead, and allow multiple users to be accessed simultaneously This service. The specific expression is implemented in the RUN function of MainsVctRead:
While (ListentHreadCount { Server = li.accept (); // Listening Echothread P = New Echothread (Server, this); // Create a specific logic object that implements the service is a class that supports threads. Thread T = New Thread (g, (runnable) P); // Put the current thread into the group T.Start (); // Start service thread ListentHreadCount ; // Modify the current thread quantity } Referring to the tools mentioned above, JNTSVC.exe can help you read the compiled .class file assembled into an EXE file, run this article and add -install parameters to automatically help you say some good service to the registry, you can pass The service manager or a fairly utility is controlled as other services. Rotation service uses the -uninstall parameters. This routine uses socket, multi-thread implementation technology to explain the implementation of Java to write NT services. Actually similar to such network services can be implemented in this specification, such as POP3 services, FTP services, and even WWW services. We have also contacted the Java application server such as Tomcat, JRUN. The startup of the NT platform is often used in the NT service form, so you can also try to write your own Java service application. Finally, if you need to debug the logic of the NT service, a variant can be used. We add a main static method in echosvc.java, then generate an instance of EchosVC, which is a standard VJ generated EXE file, using VJ debugging we can exclude hidden errors. Once done, we commented out the main static method, you can get a debugged NT service after compiling. Fourth, why use Java to write NT services Comparing VC and other "original" NT service development methods, Java development model can be faster, because almost all service frames can be achieved by extending the Services class, saving a lot of complex detail processing. The Java language provides a rich library, which can be used by ourselves, and can improve efficiency, and the written program structure is clear and easy to understand, which is convenient for future maintenance. The exception handling mode provided by Java allows us to write well and safer code. Imagine if the service process is written by VC but forgets the release of a block of memory, then the service is started for a while due to memory leakage, even the system crashes; however, the language characteristics of Java itself makes us not always enabling memory. Management, you can pay more attention to service logic itself, which is more efficient. With VC If you write multithreaded service processes, although it can be implemented, it will be quite troublesome. The multithreading of the service process is almost every performance, and the Java language itself can provide good support in this regard, and Java itself has a natural good support for the network to make a variety of network sockets. Finally, if other expansion libraries are not used, we can easily implement this service logic on other operating systems. A prepared NT service program, which can be placed to other platforms such as Linux and other platforms, as far as possible, such as Linux, other platforms, such as LINUX, etc. Close up. V. Source / * The attached zip file reports all of the examples of all engineering files, as well as the executable of the compiled NT service, you can directly test the installation of this service EXE file, service start and stop * / /*Echosvc.java/ Import com.ms.service. *; Public Class Echosvc Extends Service { Static thread mainsvc = null; // Define the main thread Public echosvc (String [] ARGS) // Construction Service { Checkpoint (1000); // Service is part of the system, as a log record, can help users understand the system failure Strunning (accept_shutdown | accept_pause_continue | accept_stop); MAINSVC = New Thread ((runnable) new mainsvcthread ()); MAINSVC.START (); System.out.Println ("The Echo Service Was Started Success"); } } / * -------------- Echosvc.java source code end ------------------- * / /*MAINSVCTHREAD.java Import java.io. *; Import java.net. *; Public Class Mainsvcthread Implements Runnable / / Implement Thread Control Multirled Interface {/ Will start a set of threads to listen to multiple service requests Public static boolean stop = false; // The internal variable controlled by the system determines the startup, pause of the service process (thread). Public static boolean pause = false; Public int ListentHreadCount = 0; // The current number of current threads supported by this service INT MAXSOCKET = 10; // The maximum number of support INT SVCPORT = 2002; // Service listening port Public void Run () { Try { While (! stop) { While (! Pause &&! stop) { {// Create a listener server Socket Server; Serversocket Li = New Serversocket (SVCPORT); // Create server-side socket ThreadGroup g = new threadgroup ("eceothreads"); // Create a set of threads System.out.Println ("echo service start ..."); // Record in the LOG While (ListentHreadCount { Server = li.accept (); // Listening Echothread P = New Echothread (Server, this); // Create a service single thread Thread T = New Thread (g, (runnable) P); // Create a new thread T.Start (); // Start service thread ListentHreadCount ; // The number of current threads } } Try { Thread.sleep (5000); // Pause 5 seconds} Catch (InterruptedException E) {} } Try { Thread.sleep (1000); } Catch (InterruptedException IE) {} } } Catch (IOEXCEPTION IOE) {} } // Run end } / * ------------- Mainsvcthread.java Source code end ------------------- * / /*Echothread.java/ Import java.io. *; Import java.net. *; / * Realize the server-side thread unit logic when each customer is connected to this NT service * / Public Class Echothread Implements Runnable / / Implementation Thread Interface { Socket so = null; // socket MAINSVCTHREAD P; // a pointer to the parent thread, the thread of the eChothread is a sub-thread created by the service thread. Public void Run () { String line; DataInputStream in; / / Input stream on the sleeve PrintWriter out; // The output stream on the sleeve is buffered. Boolean EXITFLAG = FALSE; Try { IN = New DataInputStream (So.GetinputStream ()); // Get the input stream of the socket OUT = New Print Writer (no.getoutputstream ())); Out.println ("You Have Connected to Echosvc!"); // Send greetings Out.flush (); // must refresh the content within the buffer While (line = in.readline ())! = null&! EXITFLAG) { Line = line.trim (); Line.Equalsignorecase ("quit")) {// If it is an exit command, turn off the input and output flow on the current socket. In.Close (); Out.flush (); Out.close (); p.ListentHreadCount -; // Number of service thread units for main thread Return; // Exit the current service logic line unit } Else { Out.println ("echo:" line); Out.flush (); } } In.Close (); Out.close (); p.ListentHreadCount -; } Catch (IOEXCEPTION IOE) {} } Echothread (Socket S, Minsvcthread Parent) { SO = S; P = pent; } } / * -------------- ECHTHREAD.JAVA source end ------------------- * /