java.net.BindException: Address already in use: JVM_Bind Multi Client Server

I have a Server project and a Client project. While the Server is running the first connection from client works fine. At the seccond connection the Server fires the "java.net.BindException: Address already in use: JVM_Bind " error. Is there a way to add more connections on the same port?

Server:

public class Main {

public static void main(String[] args) throws IOException, ClassNotFoundException {

    Socket pipe = null;
    while(true){

    ServerSocket s = new ServerSocket(2345);
    pipe = s.accept();

    Connection c = new Connection(pipe);
    c.start();

    }
}

}

public class Connection extends Thread{

private Socket socket = null;

Mensch jim = null;
ObjectInputStream input = null;
ObjectOutputStream output = null;
ServerSocket s = null;

public Connection(Socket s){
    socket = s;
}
   public void run(){
        try {
        input = new ObjectInputStream(socket.getInputStream());
        output = new ObjectOutputStream(socket.getOutputStream());

        jim = (Mensch) input.readObject();
        jim.setAge(33);

        output.writeObject(jim);

        input.close();
        output.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

} }

And the Client:

public class Main {

public static void main(String[] args) {
    Mensch jim = new Mensch(19, "Jim");

    System.out.println(jim.getAge());
    try {
        Socket s = new Socket("127.0.0.1", 2345);

        ObjectOutputStream clientOutputStream = new ObjectOutputStream(s.getOutputStream());
        ObjectInputStream clientInputStream = new ObjectInputStream(s.getInputStream());

        clientOutputStream.writeObject(jim);



        jim = (Mensch)  clientInputStream.readObject();

        System.out.println(jim.getAge());

        clientOutputStream.close();
        clientInputStream.close();


    } catch (ClassNotFoundException e) {
            e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

Jon Skeet
people
quotationmark

This is the problem:

while(true) {
    ServerSocket s = new ServerSocket(2345);
    pipe = s.accept();
    ...
}

You're trying to bind to the same port repeatedly. All you need to do is create a single ServerSocket and call accept on it multiple times. (I'd also move the pipe variable declaration inside the loop...)

ServerSocket s = new ServerSocket(2345);
while(true) {
    Socket pipe = s.accept();
    ...
}

people

See more on this question at Stackoverflow