Ameer
Ameer

Reputation: 600

Accepting multiple clients in Java TCP

I want to accept multiple clients in a Java TCP program. So I used a while loop to accept multiple clients. But the problem is I cannot connect the nodes with the server randomly. I used to connect the clients one by one in order. So how to use the switch case to connect the nodes with my server randomly?

My while Loop:

int port=7000;

while(true)
{
    try
    {
        node1=new ServerSocket(port+10);
        Socket check1=node1.accept();
        System.out.println("CLIENT A IS CONNECTED");
    }
    catch(Exception e)
    {
        System.out.println(e);
    }

    try
    {
        ServerSocket soc2=new ServerSocket(port+20);
        Socket check2=soc2.accept();
        System.out.println("CLIENT B IS CONNECTED");
    }
    catch(Exception e)
    {
        System.out.println(e);
    }

    try
    {
        node3=new ServerSocket(port+30);
        Socket check3=node3.accept();
        System.out.println("CLIENT C IS CONNECTED");
    }
    catch(Exception e)
    {
        System.out.println(e);
    }

    try
    {
        node4=new ServerSocket(port+40);
        Socket check4=node4.accept();
        System.out.println("CLIENT D IS CONNECTED");
    }
    catch(Exception e)
    {
        System.out.println(e);
    }

    try
    {
        node5=new ServerSocket(port+50);
        Socket check5=node5.accept();
        System.out.println("CLIENT E IS CONNECTED");
    }
    catch(Exception e)
    {
        System.out.println(e);
    }

But When I use this JavaNetBindexception is occurring when I connect it with E client.

Upvotes: 0

Views: 5726

Answers (2)

mustaphahawi
mustaphahawi

Reputation: 297

public class ThreadServer {

    static class ServerThread implements Runnable {
    Socket client = null;
    public ServerThread(Socket c) {
        this.client = c;
    }
    public void run() {
        try {
            System.out.println("Connected to client : "+client.getInetAddress().getHostName());
            client.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
    }
    public static void main(String args[]) {
        try {
            ServerSocket server = new ServerSocket(7000);
            while (true) {
                Socket p = server.accept();
                new Thread(new ServerThread(p)).start();
            }
        } catch (Exception ex) {
            System.err.println("Error : " + ex.getMessage());
        }
    }
}

Upvotes: 1

Joker_vD
Joker_vD

Reputation: 3765

ServerSocket serverSocket = new ServerSocket(port);
ArrayList<Socket> clients = new ArrayList<Socket>();
while (true) {
    clients.Add(serverSocket.accept());        
}

How about this? But you still will need several threads.

Upvotes: 2

Related Questions