Here is the code to write a serverSocket which listens on a given port. I have used a dummy Socket to change serverSocket's port dynamically. This method uses a inner class which is basically a thread and it creates a serversocket in thread by given port no. If you want to change its port dynamically just create a dummysocket to the given serversocket and alter the flag boolean variable then create new thread with new port. If any one can optimize it please add your ideas. I am not the Best. :)
Restart Your ServerSocket with dummySocket
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
public class LocalServer {
private int port;
private boolean change=true;
public int getPort(){return port;}
public void setPort(int newPort){port=newPort;}
public void setChange(boolean bool){change=bool;}
private boolean getChange(){return change;}
public Thread getServerThread(int port){
Thread t=null;
setPort(port);
return t=new Thread(new Runnable(){
public void run(){
System.out.println("Starting Server for Communication . . .");
ServerSocket serverSocket=null;
Socket socket=null;
try{
while(getChange()){
System.out.println("Flag is : "+getChange());
serverSocket=new ServerSocket(getPort());
System.out.println("Server Started SuccessFully . . .");
socket=serverSocket.accept();
System.out.println("Server Listening On "+serverSocket.getLocalPort());
service(socket);
//Thread.sleep(10000);
System.out.println("Service Called SuccessFully . . . ");
}
}catch(SocketTimeoutException sex){try {
serverSocket.close();
System.out.println("Error In Server Initialization!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error In Server Initialization!");
}}
catch(Exception ex){ex.printStackTrace();}
}
});
}
private static void service(Socket slaveSocket){
System.out.println("Service Called");
}
public static void main(String s[])
{try{
LocalServer ls=new LocalServer();
Thread serverThread=ls.getServerThread(10000);
serverThread.start();
System.out.println("Thread Started.");
Thread.sleep(1000);
ls.setChange(false);
Socket dummySocket=new Socket("localhost",10000);
System.out.println("Socket created");
serverThread=ls.getServerThread(20000);
serverThread.start();
}catch(Exception ex){}
}
}
shaikh_mshariq 2 Junior Poster in Training
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.