在Java TCP中接受多个客户端

时间:2013-02-08 11:29:48

标签: java tcp connection port

我想在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客户端连接。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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());
        }
    }
}