2

I'm trying to make something similar to a client server chat system, with mutliple clients

Server side code

public class Server{

private Socket socket=null;
private ServerSocket serversocket=null;


public Server(int port){

   Values val = new Values();
    while(true){

        try{

            serversocket=new ServerSocket(port);
            System.out.println("Server started\nWaiting for clients ...");
            socket=serversocket.accept();
            System.out.println("Client accepted");
            ProcessRequest pRequest= new ProcessRequest(socket, val);
            Thread t = new Thread(pRequest);
            t.start();              
        }
        catch(Exception e){
            System.out.println("Socket creation exception: "+e);
            break;
        }

    }   

Now when i run the server on any port to listen for connections, it is throwing exception

Server started
Waiting for clients ...
Client accepted
Socket creation exception: java.net.BindException: Address already in use (Bind failed)

But i'm able to send and receive message between the client and server without any problem.

It's showing the error but the thread starts correctly and processes the request as it should.

So, why is this exception occuring, and how to fix the same?

Class using the thread --

class ProcessRequest implements Runnable{


private DataInputStream inp=null;
private DataOutputStream oup=null;
private Socket socket=null;
private Values val=null;
private String ip;

ProcessRequest(Socket s, Values v){

    socket=s;
    val=v;
    ip=(((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress()).toString().replace("/","");
}
public void run(){

    try{
        inp=new DataInputStream(socket.getInputStream());
        oup=new DataOutputStream(socket.getOutputStream());
    }
    catch(Exception e){
        System.out.println(e);
    }   
    String line = "";
    while (!line.equalsIgnoreCase("exit")){
        try{
            line = inp.readUTF();
            // System.out.println(line);
            String[] tokens=line.split(" ");
            if(tokens[0].equalsIgnoreCase("put")){

                val.setValue(ip, tokens[1], tokens[2]);
            }
            else if(tokens[0].equalsIgnoreCase("get")){

                String value=val.getValue(ip, tokens[1]);
                oup.writeUTF(value);    
            }
        }
        catch(IOException i){

            System.out.println(i);
            return;
        }
    }
    try{
        inp.close();
        oup.close();
        socket.close();
    }  
    catch(IOException i){

        System.out.println(i);
        return;
    }  
}
1
  • Tip: Always print the stack trace of the exceptions: they tell exactly what the problem is (type of the exception) and the location where it's thrown. So, instead of guessing what happens, you would know, just by reading the stack trace. Also, don't catch Exception. Only catch the exception that are expected, and that you can handle correctly. Otherwise, let them propagate. Commented Sep 2, 2017 at 17:00

1 Answer 1

4

The ServerSocket needs only to be created for once (here in this case) and bound to the IP and Port.

What you're doing here is creating multiple ServerSockets and binding to the same IP and port. Creating different ServerSockets and binding to the same set of IP and Port combination will obviously throw this exception.

So, to make it work, please remove the ServerSocket creation line from the loop.

public Server(int port){
    Values val = new Values();
    // Add your ServerSocket code here instead of the loop
    serversocket = new ServerSocket(port);
    System.out.println("Server started\nWaiting for clients ...");
    while(true) {
        try {
            socket=serversocket.accept();
            System.out.println("Client accepted");
            ProcessRequest pRequest = new ProcessRequest(socket, val);
            Thread t = new Thread(pRequest);
            // And so on...
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @JBNizet; I had typed this answer on Mobile phone. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.