Java中的线程和服务器

时间:2014-05-11 16:06:07

标签: java multithreading

就在我认为我弄清楚线程如何在Java中运行时,我错了。我希望这台服务器能够监听客户端,但同时允许我在控制台上输入文本。

public class MultiThreadChatServerSync implements Runnable{

    private static ServerSocket serverSocket = null;
    private static Socket clientSocket = null;
    private static final int maxClientsCount = 10;
    private static final clientThread[] threads = new clientThread[maxClientsCount];

    public static void main(String args[]) {
        int portNumber = 2222;
        if (args.length < 1) {
            System.out.println("Usage<portNumber>\n");

        } else {
            portNumber = Integer.valueOf(args[0]).intValue();
        }

        try {
            serverSocket = new ServerSocket(portNumber);
        } catch (IOException e) {
            System.out.println(e);
        }
        //I thought this was the answer and it would run in the backround
        (new Thread(new MultiThreadChatServerSync())).start();


    }
    public void run() {

        while (true) {
            try {
                clientSocket = serverSocket.accept();
                int i = 0;
                for (i = 0; i < maxClientsCount; i++) {
                    if (threads[i] == null) {
                        (threads[i] = new clientThread(clientSocket, threads)).start();
                        break;
                    }
                }
                if (i == maxClientsCount) {
                    PrintStream os = new PrintStream(clientSocket.getOutputStream());
                    os.println("Server too busy. Try later.");
                    os.close();
                    clientSocket.close();
                }
            } catch (IOException e) {
                System.out.println(e);
            }
        }

    }
}

拜托。我错过了什么?

1 个答案:

答案 0 :(得分:0)

问题不是很清楚,但我建议问题是你在主线程上运行你的服务器,同时尝试从控制台接受用户输入。如果你仍想接受用户输入,我会建议另一个线程,唯一的目的是监听和接受传入的连接。

换句话说,您正在查看的架构应该是(伪代码)

服务器主题:

public void run() {
    while (connections < maxConnections) { 
        conn = accept connection

        // pass the new connection to a seperate thread
        sht = new ServerHelperThread(conn) 
        sht.start()
        connections++
    }
}

用于处理各个客户端的服务器帮助程序线程:

public ServerHelperThread(conn) {
    this.conn = conn;
}

public void run() {
    while(some condition) {
        communicate with client
    }
    conn.close()
}

主要课程:

public static void main(String[] args) {
    new ServerThread().start
    accept input from the console
}