I'm working on a multi-threaded server project and I created two classes:
1. Class that will open a server socket and loop through accepting sockets. Each time it accepts a connection it spawns a new thread on class #2.
2. This class, in the run() method will create an inputstream from the server socket and read each line coming through the server socket.
What I want to do is in CLASS #1 implement an interface that will invoke a certain method in class #1 each time a line is entered in the server socket.
How do you do this?
Here is condensed class #1:
Code:
public Library() {
ServerSocket serverSocket=null;
boolean listening=true;
try {
serverSocket=new ServerSocket(801);
while(listening) new rServer(serverSocket.accept()).start();
serverSocket.close();
} catch(Exception e) { System.exit(0); }
}
static public void main(String[] args) { new Library(); }
public void processCommand(String cmd, Thread thread){ }
Here is the run() method of class #2.
Code:
public void run() {
try {
DataInputStream in=new DataInputStream(s.getInputStream());
DataOutputStream out=new DataOutputStream(s.getOutputStream());
out.writeChars("Number of connections: ");
out.writeChars(java.lang.String.valueOf(Thread.activeCount()-2)+"\r\n");
String line=null;
while(true) {
Thread.yield();
line=in.readLine();
System.out.print("Thread ");
System.out.print(Thread.currentThread());
System.out.println(" :" + line);
command(line);
if(line.equalsIgnoreCase("exit")) {
s.close();
Thread.currentThread().stop();
}
}
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
See everything works, I just want to invoke method processCommand(String,Thread) each time a line comes in. I think I need to create an interface and implement on class #1, but I've never done that before. How?