Make the Java program into Windows Service

xiaoxiao2021-03-06  103

Preparation for Java Writing Service

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, after installing the SDK, you can see there in the JNTSVC directory in the installation directory. This directory contains the service.zip file. It is actually a NT Services class library framework, encapsulated some NT service implementation details, making us 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 it, here is probably: assemble all Class files in the current directory into a NT service process exe file, file named echosvc.exe, service startup in Echosvc In .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. ==

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);

SetRunning (accept_shutdown | accept_pause_continue | accept_stop); // This service accepts commands on service control

MAINSVC = New Thread ((runnable) 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. ==

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.

=====================================================================================================================================================

The method of modifying the registry can be considered, but Java has not tried.

Inside HKEY_LOCAL_MACHINE / SYSTEM / Controlset001 / Services, please find a little bit of primary key, export, modify the reg file, rename the display name inside you asked for the service name, rename the imagePath to your C: /jdk/java.exe - CP ... this look

Note: I have not tried Java, but other EXE services, I have done this method (such as the Mysql service installed under another WIN), everything OK.

======================== Utilization tool:

A gadget called "javaexe", you can register a service, it is very convenient

转载请注明原文地址:https://www.9cbs.com/read-126710.html

New Post(0)