How to use Java to write NT Services

Source: Internet
Author: User

 


Content Description: This article uses examples to explain how to use Java's features to quickly write secure and reliable NT services, how to implement Java multithreading, and how to use sockets to implement network services.

I. Introduction to NT Services

The so-called NT Service is actually a special type of application called the NT Service. In fact, it is a process that can automatically start with a certain identity when the system starts. Such as FTP server, HTTP server, and offline printing are provided in the form of NT services. This is actually similar to the Unix root daemon process. In summary, the NT Service has the following features:

1. It can be started automatically without interactive startup. This is an important feature for servers. Of course, you can decide whether the service is self-started or even block a service.
2. the NT Service has no user interface, which is basically similar to a DOS program. Because the NT Service must run for a long time, you do not want to have your own interface like the common win32 process. However, the NT Service can interact with the user interface, which is a special service process. You can view the service process through the task manager of NT.
3. the NT Service is managed through the SCM interface. The SCM interface functions are required for installation, start, stop, and removal. The service controller of the Control Panel uses the SCM interface to manage all services in the system. In addition, there are some program commands that can control the service, such as 、SCM.exe, such as net.exe, Server Manager, and so on.
4. These processes run in a certain identity to facilitate access to server resources. Generally, the LocalSystem account in the domain is used to run the program. This account has full access permissions to most resources on the machine (unless otherwise prohibited), which ensures that the service program is "powerful ". However, some services run with special accounts. You can also set a service account.
5. the system automatically runs in the thread mode. Generally, it only occupies more system resources. This is different from common processes. If the thread mode is not used, generally, processes consume the entire CPU resource. Generally, tasks that need to exist from time to time and do not consume too much resources are most suitable for Service implementation.

2. Preparation of Java compiling services

1. As a localized implementation, the Java program implementing the NT Service is certainly not 100% pure Java, and the standard library alone cannot implement the goal of compiling the NT Service, therefore, MS provides a set of sdks for Java (Microsoft SDK for Java 4.0 is used in this article) and describes how to use the extended class libraries and corresponding tools provided by MS, implement Programs that meet the requirements of the Windows platform. This includes the library API framework required for implementing the NT Service and the tool for assembling the class file compiled by Java into a standard NT Service Program. You can find the SDK download path from www.microsoft.com/java.

2. After installing sdk, you can see that the installation directory contains the jntsvcdirectory, which contains the service.zip file. It is actually a Class Library Framework of NT services. It encapsulates some NT Service implementation details so that we can follow the framework to implement the details we care about. Expand service.zip to the system of the development machine and install the Service library to the Java extension library WinntjavaTrustLib. If you develop the library in other operating systems, follow the instructions in this system directory to install the file.
3rd has a jntsvc.exe file under the Directory, which is the meaning of Java NT Service. She helps you to assemble the compiled class files implemented by the framework provided by the SDK into a standard NT Service Executable File. JntSvc helps us set all the features required by the NT Service Program on the basis of the compiled. class file. It is an important tool. Getting the NT service depends on how to use it effectively. To make it easy for us to adjust the full path of the jntsvc.exe directory from the control window of another directory, we add the path environment variable. This allows you to set environment variables on the Advanced properties page of system properties.

4. Write the code as required, compile the Java program, and obtain the class file. Of course, we will not start her in Vj Studio because it does not have an executable file portal and the system cannot start her. To obtain the NT Service Program, run the following command in the console window of the directory where the class file is located: X:> jntsvc *. class/OUT: ECHOSvc.exe/SVCMAIN: EchoSvc "/SERVICENAME: ECHOSvc ". For specific Jntsvc parameters, let's take a look at jntsvc -? In this example, the startup entry of the service is echosvc. class, and the corresponding service name in the registry is EchoSvc specified by the/Servicename parameter. If multiple NT services need to be assembled in an Exe file, you can specify the display name of each service after the/Out parameter. The/SVCMAIN parameter specifies the service endpoint. The so-called endpoint refers to the class instance from which the service starts at the beginning. "/SERVICENAME:" parameter specifies the name of the Service to appear. These are all required information for the jntsvc.exe utility to assemble the service. Based on this information, the compiled. class file is required to obtain an executable file in win32 format.

It should be noted that the execution of this exe file must have a JVM, and she actually implements service provision by interpreting. class. If you need another extension package, you can specify the location of another extension package by using the/Classpath parameter. Therefore, JVM must exist on the machine where the NT Service compiled by Java is installed. If you have IE5.x, you don't have to worry about this problem. The IE Core Component already includes JVM. However, if you are in IE6, You need to download JVM from the MS website. It is more convenient to install the SDK for Java on the server.

5. If no error occurs, you will get an executable file echosvc.exe. Like most service executable files, it can install itself into the system: echosvc.exe-install. This process will add some projects to the system registry, especially for service projects, SCM can also list this service. We can use the dos nt Service Control Command Net start/stop in the console to test whether the service is actually controlled in the standard way like a common service, of course, starting or stopping the service in the service manager is not a problem.

Iii. Example of Echo service

When the system loads the service process, the entry is in the EchoSvc constructor. We can see that this constructor has parameters similar to the main () Entry of the general program.
Import com. ms. service .*;

Public class EchoSvc extends Service

{Static Thread mainSvc = null; // defines the main service Thread

Public EchoSvc (String [] args) // construct this service

{

CheckPoint (1000 );

SetRunning (ACCEPT_SHUTDOWN | ACCEPT_PAUSE_CONTINUE | ACCEPT_STOP); // service control commands accepted by the Service

MainSvc = new Thread (Runnable) new MainSvcThread ());

MainSvc. start ();

System. out. println ("The Echo Service Was Started Successfully! "); // Records events, which can be viewed by the event viewer.

}

}

A CheckPoint is a Service synchronization method. It indicates that the system is changing the Service status and needs to wait for 1 second. Here we start a thread, which is actually equivalent to a process. It is the main thread of the service process. In this thread, we respond to SCM's control over this service. The general expression is:

Public class MainSvcThread implements Runnable // implement thread control

{

Public static boolean STOP = false; // internal variables controlled by the system determine the startup and suspension of service processes (threads ).

Public static boolean PAUSE = false;

Public void run ()

{

While (! STOP)

{

While (! PAUSE &&! STOP)

{

... // Here is the service control logic, which will be enriched below
}

Try

{Thread. sleep (5000); // pause or stop after sleep for 5 seconds}

Catch (InterruptedException e)

{}

}

Try

{Thread. sleep (1000 );}

Catch (InterruptedException ie)

{}

}

} // Run ends

}

In Service Logic Control, we implement the Echo service. Our Echo service listens to port 2002, receives any line of input from the client, and then adds "Echo:" To return the result. If the client enters a quit phrase, the Service determines that this is the command for the customer to close the socket. It will automatically close the current socket connection and stop the service for 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 (); // gets the input stream of the socket.

Out = new PrintWriter (new DataOutputStream (so. getOutputStream ()));

Out. println ("You have connected to EchoSvc! "); // Send greetings

Out. flush ();

While (line = in. readLine ())! = Null) // read

{

Line = line. trim ();

If (line. Pipeline signorecase ("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 displays the characters sent by the customer back to the customer, and adds the Echo: prefix to indicate that the content is returned from the server. If the customer enters "quit", this indicates that the server is required to stop the service.

How to debug the NT service process project. If you call this function directly to provide the ECHO socket service of the client, there is no logic error, but it cannot be accessed by multiple users at the same time. To provide multiple services and allow multiple users to connect to the server at the same time (in this case, many network services are indispensable), we can put this logic in the thread created by MainSvcTread.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.