I am developing an application in which i want to set up ServerSocket's port on requirement. I have given an interface which accepts port number and this port number i want to assign my previously running serverSocket but serverSocket.accept() method blocks and I am unable to execute the code after accept what can I do Please Help. Code Is As Above :

package comm;


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.InetAddress;


import proto.ErrorProvider;
public class LocalServer implements Runnable{
private ServerSocket serverSocket=null;
private Socket slaveSocket=null;
private int port;
private boolean change=false;
public int getPort(){return port;}
public void setPort(int newPort){port=newPort;}
public void setChange(boolean bool){change=bool;}
public void run() {
try{
// TODO Auto-generated method stub
if(serverSocket==null){


serverSocket=new ServerSocket(getPort());
ErrorProvider.getPlainPnl("Server Started On :"+getPort());
slaveSocket=serverSocket.accept();
System.out.println(slaveSocket.getLocalPort());
ErrorProvider.getPlainPnl("Accepted");
if(change){
serverSocket.close();
serverSocket=null;
//serverSocket=new ServerSocket(getPort());
ErrorProvider.getErrorPnl("In Change");
restart();
}


}


}catch(Exception ex){ErrorProvider.getErrorPnl(ex.getMessage());}
}
public void restart(){
System.out.println("Restart Called... ");
run();
}
public void interrupt(){
System.out.println("Interrupt Called... ");
this.interrupt();
}
public void stop(){
try{
System.out.println("Stop Called... ");
serverSocket.close();
serverSocket=null;
}catch(Exception ex){ErrorProvider.getErrorPnl(ex.getMessage());}
}
public void sleep(long time){
try{
System.out.println("Sleep Called... ");
Thread.sleep(time);
stop();
restart();
}catch(Exception ex){ErrorProvider.getErrorPnl(ex.getMessage());}


}
public void start(){
run();
}


/*public  static void main(String s[])
{try{
LocalServer ls=new LocalServer();
ls.setPort(10000);
System.out.println("Thread Started.");
ls.start();


ls.interrupt();
ls.setChange(true);
ls.setPort(20000);
Socket dummySocket=new Socket("localhost",10000);
System.out.println("Socket created");
ls.sleep(1000);
}catch(Exception ex){ErrorProvider.getErrorPnl(ex.getMessage());}


}
*/
}:(

Set a socketTimeout on the ServerSocket and place the accept in a while loop so that it will "interrupt" every once in a while.

I.E.

ServerSocket ss = .....
ss.setSoTimeout(1000);
while(true) {
  Socket s = ss.accept();
  // do whatever you normally do with s (if it is defined);
  // check whatever you want to check to possibly reassign your ServerSocket and then do so
}
commented: Perfect Solution Thanx +2

run server socket in separate thread.

For Those who want to see the answer from this forum below is the code. Use this method and add setport method for setting port value from other class. create new Thread Class's Object with the given method put this. You can also use while loop or another thread to do so.

public Thread getServerThread(){
Thread t=null;
return t=new Thread(new Runnable(){
public void run(){
ServerSocket serverSocket=null;
Socket socket=null;


try{
serverSocket=new ServerSocket();
serverSocket.setSoTimeout(20000);
//timeout as per your requirement
serverSocket.bind(new InetSocketAddress("localhost",getPort()));
//your ip address and port                  System.out.println("Server Started . . ."+serverSocket.getSoTimeout());
socket=serverSocket.accept();
//your logic to do socket operations
}catch(SocketTimeoutException sex){try {
serverSocket.close();
System.out.println("ServerSocket Expired . . .");
} catch (IOException e) {
e.printStackTrace();
}}
catch(Exception ex){ex.printStackTrace();}
}
});
}

Demo Use of this method :

while(true){
Thread thread=tt.getServerThread();
thread.start();
Thread.sleep(200);
//sample sleep operation to create serversocket as per your requirement
//add you logic to set port value while server is listening on another port
thread.stop();
}

Other Way without Implementing serversocket time out is little tricky but it is also can be implemented. Here Is the Code :-

import java.io.IOException;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;


public class LocalServer {
private int port;
public  ServerSocket serverSocket=null;
private boolean change=false;
public int getPort(){return port;}
public  void setPort(int newPort){port=newPort;}
public  void setChange(boolean bool){change=bool;}
public LocalServer(int portn){setPort(portn);}
private  boolean getChange(){return change;}
public  Thread getServerThread(){
Thread t=null;
return t=new Thread(new Runnable(){
public void run(){
System.out.println("Starting Server for Communication . . .");


Socket socket=null;


try{
serverSocket=new ServerSocket(getPort());
while(true){
System.out.println("Flag is : "+getChange());
if(getChange() && serverSocket!=null){
serverSocket.close();
serverSocket=null;
serverSocket=new ServerSocket(getPort());
System.out.println("In Condition");
}
socket=serverSocket.accept();
System.out.println("Server Listening On "+serverSocket.getLocalPort());
service(socket);
socket.close();
System.out.println("Service Called SuccessFully . . . ");
}


} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error In Server Initialization!");
}
catch(Exception ex){ex.printStackTrace();}
}
});
}
private  void service(Socket slaveSocket){


System.out.println("Service Called");
}
public void changePort(int newPort){
try{
int prePort=this.getPort();
System.out.println("Changing Server Port "+prePort+" To "+newPort+" Port");
this.setPort(newPort);
this.setChange(true);
Socket dummySocket=new Socket("localhost",prePort);
dummySocket.close();
Thread.sleep(2000);//time to chage serverconfiguration according to the flag
this.setChange(false);
}catch(ConnectException conex){}
catch(Exception ex){ErrorProvider.getErrorPnl(ex.toString());}
}
public boolean checkPort(int prt){
try{
this.setChange(true);
Socket dummySocket=new Socket("localhost",prt);
dummySocket.close();
return true;
}catch(java.net.ConnectException conex){return false;}
catch(Exception ex){ErrorProvider.getErrorPnl(ex.toString());return false;}



}
public  static void main(String s[])
{try{
LocalServer ls=new LocalServer(10000);//initial port number of the server
//creates serversocket with 10000 port number
Thread serverThread=ls.getServerThread();
serverThread.start();
//server started
Thread.sleep(3000);     //proper time to server Startup


ls.changePort(40000);
ls.changePort(50000);
if(ls.checkPort(40000)){ErrorProvider.getInfoPnl("Port is OK");}
else
{ErrorProvider.getInfoPnl("Port is not OK");}


}
catch(Exception ex){ErrorProvider.getErrorPnl(ex.getMessage());}


}


}

Waiting for your suggestions Friends.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.