多线程似乎没有工作

时间:2014-03-31 01:48:23

标签: java multithreading

我有2个类,一个服务器和一个客户端。服务器使用多个线程来接受许多客户端。所以x客户端可以加入同一台服务器。但是,为了尝试从客户端方法中识别线程,我似乎发现它不会使多个线程作为ID对所有客户端都是相同的。我的代码如下:

SERVER:

public class Server
{
    ServerSocket serverSocket;
    int portNumber;
    public static volatile String userInput;
    public volatile int noOfClients = 0;

public static void main(String[] args)
{
    Server s = new Server();
    s.startup();
}


/**
 * Start the server on the user picked port
 */
public void startup()
{   
    try 
    {
        System.out.println("Enter a port");
        Scanner dif = new Scanner(System.in);
        portNumber = Integer.parseInt(dif.nextLine());
        dif.close();

        serverSocket = new ServerSocket(portNumber);
        newThread();
    }
    catch (IOException e) {
        System.out.println("Error");
        System.exit(0);
    }
}


public void newThread()
{
    Thread thread =new Thread()
    {

        public void run()
        {   
            while(true) {
                try {

                    accept();
                } catch (Exception e) {
                    System.out.println("Error");
                }
            }
        }
    };
    thread.start();
}

public void accept()
{
    try
    {
        Socket clientSocket = serverSocket.accept();
        new Thread(new ClientSocket(clientSocket)).start();
        System.out.println("A new client has just connected.");
        noOfClients++;

    } catch(IOException e)
    {
        System.out.println("Error");
        System.exit(0);
    }
}


class ClientSocket implements Runnable {
    Socket clientSocket;

    public ClientSocket(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    public void run() {
        {
            try
            {
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);                   
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

                while (true)
                {
                    userInput = in.readLine();
                }

            } catch (IOException e)
            {
                System.out.println("Error");
            }
        }
    }
}
}

客户端:

public class Client
{
    Socket clientSocket;
    public static int threadName;


public static void main(String[] args) throws IOException {
    String hostName = args[0];
    int portNumber = Integer.parseInt(args[1]);


    try {
        Socket serverSocket = new Socket(hostName, portNumber);
        PrintWriter out = new PrintWriter(serverSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

        Thread thread = Thread.currentThread();
        System.out.println("RunnableJob is being run by " + thread.getName() + " (" + thread.getId() + ")");
        String userInput;

        while ((userInput = stdIn.readLine()) != null)
        {

            out.println(userInput);
            System.out.println("Server: " + userInput);
        }

    } catch(UnknownHostException e) {
        System.out.println("error in host");
    } catch(IOException e) {
        System.out.println("error in IO");
    }


}
}

运行两个单独的客户端时,

System.out.println("RunnableJob is being run by " + thread.getName() + " (" + thread.getId() + ")");

代码行打印出来。我如何修复它,以便在自己的UNIQUE线程内启动每个新的客户端连接。所以2个客户总共有2个线程?谢谢:))

2 个答案:

答案 0 :(得分:1)

首先,您正在检查客户端的线程ID,这些客户端彼此分开,因此不起作用。

然而,使用线程ID并不是识别客户端的好方法。相反,为什么不保留客户端数量,然后当一个新客户端加入时,递增数字并将客户端对象的数字作为id。

答案 1 :(得分:0)

多个客户端将在不同的端口no连接服务器。您可以使用该端口号来区分客户端。

如果需要,您可以将ClientSocket存储在某个位置,以便将来检索每个客户的其他信息,如下面的代码所示。

以下是代码:

private static HashMap<Integer, ClientSocket> clientInfo = new HashMap<Integer, ClientSocket>();
class ClientSocket implements Runnable {
    Socket clientSocket;

    public ClientSocket(Socket clientSocket) {
        this.clientSocket = clientSocket;
        System.out.println(clientSocket.getPort());
        clientInfo.put(clientSocket.getPort(), this);
    }
    ...

详细了解Java Server with Multiclient communication