I have the follwing code which is a thread pool in java which accepts only one client
public class ServerThread implements Runnable {
ServerSocket serverSocket;
Socket clientSocket;
protected boolean isStopped = false;
int serverPort = 6500;
private String serverIpAddress = "127.0.0.1";
DataInputStream is;
ObjectOutputStream os=null;
protected BlockingQueue queue = null;
protected ExecutorService threadPool2 =
Executors.newFixedThreadPool(1);
public ServerThread(BlockingQueue queue) {
this.queue=queue;
}
public void run() {
try {
InetSocketAddress serverAddr = new InetSocketAddress(serverIpAddress, serverPort);
serverSocket = new ServerSocket();
serverSocket.bind(serverAddr);
System.out.println("s-a creat");
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
e.printStackTrace();
}
while(!isStopped()){
clientSocket=null;
try{
clientSocket = serverSocket.accept();
}
catch(Exception e)
{
e.printStackTrace();
}
WorkerServerRunnable workerRunnable = new WorkerServerRunnable(queue,clientSocket);
this.threadPool2.execute(workerRunnable);
}
this.threadPool2.shutdown();
System.out.println("Server Stopped.");
}
private synchronized boolean isStopped(){
return this.isStopped;
}
public synchronized void stop() {
this.isStopped = true;
try {
this.serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
}
But the problem is that I cannot get my server in ON state.
I mean once I press run I get the following error:
java.net.SocketException: Socket is not bound yet
at java.net.ServerSocket.accept(Unknown Source)
at servers.ServerThread.run(ServerThread.java:60)
at java.lang.Thread.run(Unknown Source)
java.net.BindException: Address already in use: JVM_Bind
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at servers.ServerThread.run(ServerThread.java:44)
at java.lang.Thread.run(Unknown Source)
Even if I shutdown my whole app and run it again still the same error….has anyone any idea why?Thank u!
Some other program is already using port 6500. Check that you’re not running another instance of your program.
Try running
to see what processes are using which ports. Make sure the port on which you wish to listen is not listed in the output from
netstat.