0

我想在 Java TCP 程序中接受多个客户端。所以我用一个while循环来接受多个客户端。但问题是我无法将节点随机连接到服务器。我曾经按顺序一一连接客户端。那么如何使用 switch case 将节点与我的服务器随机连接?

我的while循环:

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);
    }

但是当我使用JavaNetBindexception它时,当我将它与 E 客户端连接时就会发生这种情况。

4

2 回答 2

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

这个怎么样?但是你仍然需要几个线程。

于 2013-02-08T11:34:55.133 回答
1
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());
        }
    }
}
于 2013-02-08T11:45:18.230 回答