Search code examples
javaservicedaemon

How to run a java class as a socket server


This sounds like a noob question for me but I need to ask it.

So I coded a small file server application, which listens to port 21 through sockets. It receives byte arrays, and then write files (usually jpg files), works great on IDE.

I want to put it live, running permanently in the server so remote applications can send the byte arrays to the port 21 on which my server app is listening.

The physical server OS is CentOS 6, but I can set Ubuntu and many redhat flavors of Linux (you know cloud servers).

So, how can I code a daemon (maybe a shell script) to keep this java class as a service? say I can write:

service jMyFileApp {start|stop|restart|status}

I tried googling it but, I'm kind of lost... I don't know how to ask it to Google


Solution

  • Here's the service script I use to start and stop Tomcat (which is basically equivalent to what you are trying to do):

    #! /bin/sh
    case "$1" in
    start)   /usr/local/jakarta/tomcat/bin/startup.sh ;;    
    stop)    /usr/local/jakarta/tomcat/bin/shutdown.sh ;;
    restart) /bin/sh $0 stop
    /bin/sh $0 start ;;
    *)   echo "Usage: $0 {start|stop}"
    exit 1 ;;
    esac
    

    That is under /etc/init.d/tomcat. So basically there are shell scripts that understand how to start and stop Tomcat, and the service script just delegates to those.

    In your case, just provide some simple shell scripts that can start/stop your custom server (that will likely be the most challenging part), and then invoke them from the service script (i.e. vi /etc/init.d/jMyFileApp, copy/paste the Tomcat script above, edit the paths as appropriate to point at your custom startup scripts, and then chmod a+rx /etc/init.d/jMyFileApp).