Hello all,
I am building a java application that listens on 2 ports simultaneously and is also capable of multithreading. How Im doing this is as follows. I have a very basic GUI in PortApp.java which takes in 2 integers through 2 textfields and also has a listen button. So when the listen button is clicked, the following code is executed.
jTextField1.disable();
jTextField2.disable();
int port = Integer.valueOf(jTextField1.getText());
int port1 =Integer.valueOf(jTextField2.getText());
int count = 0;
try{
foo(port,port1);
while (true) {
//Socket connection = socket1.accept();
thread.start();
thread1.start();
}
}
catch (Exception e) {}
And the method foo() is as follows
public void foo(int a, int b){ //function to get the port numbers as integers and to declare 2 sockets for the ports.
int port=a;
int port1=b;
int count=0;
try {
socket1 = new ServerSocket(port);
} catch (IOException ex) {
}
try {
socket2 = new ServerSocket(port1);
} catch (IOException ex) {
}
//System.out.println("MultipleSocketServer Initialized");
Runnable runnable = new MultipleSocketServer(socket1, ++count);
Runnable run = new MultipleSocketServer(socket2, ++count);
thread = new Thread(runnable);
thread1 = new Thread(run);
}
where socket1 and socket2 are ServerSocket instances. Control then transfers to another class MultipleSocketServer which inturn does the other backend work, once the sockets are established.
The run() of MultipleSocketServer class is as follows
public void run() {
while(true){
try {
Socket incoming=connection.accept();
BufferedInputStream is = new BufferedInputStream(incoming.getInputStream());
int character;
while((character = is.read())!=-1) {
//DO SOMETHING
}
incoming.close();
SYstem.out.println("Client DC'ed");
//CONTINUE WITH OTHER EXECUTIONS
}
and the constructor for MultipleSocketServer is
MultipleSocketServer(ServerSocket s, int i) {
this.connection = s;
this.ID = i;
}
Now the above listener code does support multiple clients at the same time. And I thought that it would and should print the 'cient DC'ed prompt message' whenever any of the 'many simultaneously connected on same port' clients disconnects, but this does not seem to happen, It does not print out the prompt until the last client is connected to that port instance and once that client disconnects, then it prints out the prompt messages of all the clients. SO in essence, even if any particular client disconnects, the propmt message corresponding to that client is not printed until the very last client disconnects, thereby making the socket 'free'. Any pointers on how i can resolve this and print out the prompts as and when any of the simultaneously connected clients disconnects without waiting for all of them to disconnect, would be of great help.
FYI, I am simulating the above environment using multiple Hyperterminal instances.
CHEERS