A simple service program
Introduction
A simple service program to show usage of Service type of applications.
This demo program listens on a PORT, accepts connections and serves like a HTTP server. It responses a simple message on any request.
1. Edit a java source file: "X:\demos\src\hello\HelloService.java"
package hello;
import java.io.*;
import java.net.*;
public class HelloService {
// port to listen
public static int PORT = 8080;
public static void main(String[] args) throws IOException {
// load port settings from properties
PORT = Integer.parseInt(System.getProperty("hello.service.port",
String.valueOf(PORT)));
// listen
ServerSocket listener = new ServerSocket(PORT);
System.out.println("HelloService started.");
// accept a connection
Socket socket;
while(null != (socket = listener.accept())) {
// open a thead to serve
final Socket fsocket = socket;
Thread t = new Thread(new Runnable() {
// A simple variable to let response changing
int n = 1;
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
fsocket.getInputStream(), "iso-8859-1"));
PrintStream out = new PrintStream(
new BufferedOutputStream(fsocket.getOutputStream()));
// Get any http request
while(readHttpRequest(in)) {
// Response a simple message
String msg = "<font color='red'>Hello, this is a demo service," +
" you have requested " + n++ + " times.";
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html; charset=iso-8859-1");
out.println("Content-Length: " + msg.length());
out.println();
out.println(msg);
out.flush();
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try { fsocket.close(); } catch (IOException e) { }
}
}
// Get any http request
private boolean readHttpRequest(BufferedReader in) {
try {
String line;
while((line = in.readLine()) != null)
{
if(line.length() == 0) {
return true;
}
}
}
catch (IOException e) {
}
return false;
}
});
t.setDaemon(true);
t.start();
}
}
}
2. Enter "X:\demos" directory and compile it to a class file:
X:\>cd demos X:\demos>javac src/hello/HelloService.java
3. Make a jar file:
X:\demos>jar -cvf helloservice.jar -C src .
4. Use Jar2Exe to generate exe file for Windows and Linux separately:
X:\demos>j2ewiz helloservice.jar /m hello.HelloService /type service /service HelloService X:\demos>j2ewiz helloservice.jar /m hello.HelloService /type service /platform linux
5. Install the program as a Service on Windows and Linux respectively:
helloservice /install
6. Start the service by 'net' command on Windows, by 'service' command on Linux:
net start HelloService
Now open a browser to visit http://localhost:8080 to test the service.
7. Download the program for reference.
- helloservice.zip - 168k, download this demo program.
- demos.7z - 5.75M, all demos in one file.
See Also
- See Run as Service page for more details about Service type of applications.
