/**
* sample implementation of an Ivy Daemon, like ivyd.
* @author Yannick Jestin
* @author http://www.tls.cena.fr/products/ivy/
*/
package fr.dgac.ivy ;
import java.io.*;
import java.net.*;
import gnu.getopt.Getopt;
/**
* toy tool to send anonymous messages to an Ivy bus through a simple tcp
* socket.
* IvyDaemon runs in the background and forwards all the incoming trafic to
* the bus, line by line. The default port is 3456.
*
* @author Yannick Jestin
* @author http://www.tls.cena.fr/products/ivy/
*
* changelog:
* 1.0.12
* - class goes public access !
*/
public class IvyDaemon implements Runnable {
public static int DEFAULT_SERVICE_PORT = 3456 ;
ServerSocket serviceSocket;
boolean isRunning=false;
Ivy bus;
public static void main(String[] args) {
Getopt opt = new Getopt("IvyDaemon",args,"b:dp:");
int c;
int servicePort = DEFAULT_SERVICE_PORT;
String domain=Ivy.DEFAULT_DOMAIN;
while ((c = opt.getopt()) != -1) switch (c) {
case 'b':
domain=opt.getOptarg();
break;
case 'd':
System.setProperty("IVY_DEBUG","yes");
break;
case 'p':
String s="";
try {
servicePort = Integer.parseInt(s=opt.getOptarg());
} catch (NumberFormatException nfe) {
System.out.println("Invalid port number: " + s +
"switching to default port "+servicePort);
}
break;
default:
}
IvyDaemon d = new IvyDaemon(domain,servicePort);
}
public IvyDaemon(String domain,int servicePort) {
// connexion to the Bus
try {
bus=new Ivy("IvyDaemon","IvyDaemon ready",null);
System.out.println("broadcasting on "+domain);
bus.start(domain);
serviceSocket = new ServerSocket(servicePort) ;
System.out.println("listening on "+servicePort);
isRunning=true;
(new Thread(this)).start(); // loops on the service Socket, awaiting connexion
} catch (IvyException ie) {
System.out.println("Caught an exception. quitting. "+ie.getMessage());
} catch (IOException ioe) {
System.out.println("Caught an IOexception. quitting. "+ioe.getMessage());
}
}
/*
* the service socket reader.
* it could be a thread, but as long as we've got one ....
*/
public void run() {
// System.out.println("IvyDaemon Thread started"); // THREADDEBUG
while(isRunning){
try {
Socket socket = serviceSocket.accept();
new SubReader(
new BufferedReader(new InputStreamReader(socket.getInputStream())));
} catch( IOException e ) {
System.out.println("IvyDaemon DEBUG TCP socket reader caught an exception " + e.getMessage());
}
}
// System.out.println("IvyDaemon Thread stopped"); // THREADDEBUG
}
class SubReader extends Thread {
BufferedReader in;
SubReader(BufferedReader in) {this.in=in;start();}
public void run() {
// System.out.println("Subreader Thread started"); // THREADDEBUG
String msg = null;
try {
while ( ((msg=in.readLine()) != null )) { bus.sendMsg(msg); }
} catch (IOException ioe) {
System.out.println("exception ..." + ioe.getMessage());
}
// System.out.println("Subreader Thread stopped"); // THREADDEBUG
}
} // subclass SubReader
} // class IvyDaemon
// EOF