Hello,
I have a Threaded
Java server, which needs to access multiple clients.
The server is started at a port specified from another class.I invoke the constructor of the Java server only once and start the server at the specified port.Now,i would like my server to listen continuously to my client, whenever the client sends a request.
The code is attached below:
<CODE>
import java.io.*;
import java.net.*;
public class JavaServer extends Thread{
static int port;
Dispatcher dispatch;
ServerSocket server_socket;
Socket s;
/**
* Deafult constructor
*/
public JavaServer(){ }
/**
* Overloaded Constructor,starts the server at the specified port
* @param p int
* @param dispatch Dispatcher
*/
public JavaServer(int p,Dispatcher dispatch) {
this.dispatch=dispatch;
port = p;
try {
System.out.println("before Socket port..");
server_socket = new ServerSocket(port);
System.out.println("Server started on port " +port);
}
catch (IOException io) {
System.out.println(" IO Exception " + io);
io.printStackTrace();
}
while(true){
while(this.acceptConn()){
System.out.println( "**** Client's connection accepted !! *** " );
start();//<b> $$$$$$$$$$$$$$$$$$I get the error java.lang.IllegalThreadStateException here </b>$$$$$$$$$$$$$$$$$$$$$
}
}
}
public boolean acceptConn(){
System.out.println("within accept........");
boolean bool=false;
try {
s = server_socket.accept();
System.out.println(
"server side i/p and o/p stream associated with socket...");
bool=true;
}
catch (UnknownHostException io) {
System.out.println(" Unknown host " + io);
io.printStackTrace();
}
catch (IOException io) {
System.out.println(" IO Exception " + io);
io.printStackTrace();
}
return bool;
}
/**
* This method is invoked when the Receiver is started.
*/
public void run(){
DataOutputStream dos = null;
int i = 0;
InputStream is = null;
BufferedReader bf = null;
try {
dos = new DataOutputStream(s.getOutputStream());
is = s.getInputStream();
bf = new BufferedReader(new InputStreamReader(is));
System.out.println("Waiting for response.." + bf);
long start=System.currentTimeMillis();
System.out.println(" **** Start time is **** "+ start);
dispatch.dispatchMessage(bf,start);
}
catch (IOException io) {
System.out.println(" IO Exception " + io);
io.printStackTrace();
}
}//end of run()
}//end of class
</CODE>
I understand that start() is invoked only once in the lifecycle of Thread.But,now,i have to invoke it multiple times.How is it done??
Thanks!!
[ April 29, 2004: Message edited by: Priya Vasudevan ]
[ April 29, 2004: Message edited by: Priya Vasudevan ]