Java的;试图使服务器接受多个客户端连接

时间:2012-03-03 20:49:30

标签: java multithreading sockets

我最近开始尝试建立服务器 - 客户端连接。我能够建立一对一连接没有问题,但现在我正在尝试制作一个接受多个客户端的服务器,我遇到了一个问题,我不能让服务器听取连接,而有一个成立......我不确定我是否清楚自己,但这是我的代码:

- 等待连接的主循环:

public class ChatMultiServer {

public static void main(String []args){

    int socknum = 124;
    ServerSocket serverSocket;
    Socket clientSocket;

    while(true){

    ////opens socket
    try{
        System.out.println("Opening port...");
        new ServerSocket(124).close();
        serverSocket = new ServerSocket(socknum);
    }catch(Exception e){System.out.println("Error 101 = failed to bind to port "+socknum+"."); break;}
    //////accepts connection
    try{
        System.out.println("Waiting for connections...");
        clientSocket = serverSocket.accept();
    }catch(Exception e){System.out.println("Error 102 = failed to accept port "+socknum+"."); break;}
    /////
    try{
        System.out.println("Initializing thread...");
        new Thread(new CMSThread(clientSocket));
    }catch(Exception e){System.out.println("Error 103 = failed to create thread."); break;}
    try{
        serverSocket.close();
    }catch(Exception e){System.out.println("Error 105 = failed to close socket.");}
    }
}

}

- 处理连接的线程:

public class CMSThread extends Thread{
Socket socket;
BufferedReader in;
PrintWriter out;
String username;
char EOF = (char)0x00;
public CMSThread(Socket s){
    socket = s;
    run();
}
public void run(){
    try{
    System.out.println("Setting up streams...");
    in = (new BufferedReader(new InputStreamReader(socket.getInputStream())));
    out = new PrintWriter(socket.getOutputStream());
    }catch(Exception e){System.out.println("Error 204 = failed to get streams");}
    try{
        out.print("Welcome! you can quit at any tyme by writing EXIT.\nLet me introduce myself, I'm 'testprogram 1', but that doesn't really matter since you'll do the talking.\nWhat's your name?"+EOF);
        out.flush();
        username = in.readLine();
        out.print("<b>"+username+"</b>, that's a nice name.\nWell, i'll shut up now. Have fun talking to yourself while whoever is running the server observes your conversation.\n"+EOF);
        out.flush();    
    }catch(Exception e){System.out.println("Are you effin kidding me!? -.-   whatever... Error 666 = failed to chat.");}
}

}

我的问题再一次是,当服务器与客户端建立连接时(我正在为客户端使用actionscript只是因为它更容易制作GUI),它只是等待线程完成运行才能启动循环再次。我正试图在线程处理聊天的同时使其循环。

我在想也许我需要为循环创建一个线程以及处理连接的线程,但我不确定我将如何做到这一点...如果我的话请告诉我假设有些正确,如果是的话,对答案的一些指导会很好。

PS:我很抱歉,如果我的代码有点乱,或者这是一个愚蠢的问题,我有一段时间没有制作java程序......

1 个答案:

答案 0 :(得分:2)

你实际上并没有开始新的主题 - 你只是直接调用run()。据我所知,这意味着您将在创建每个CMSThread对象的主线程中执行run()

要启动主题,您必须致电thread.start()

另外,我不确定你为什么要将CMSThread包装在另一个线程中 - CMSThread扩展Thread以便它可以自己启动。包装器线程也没有启动。

所以你需要:

        new CMSThread(clientSocket).start();

并从run()

的构造函数中删除CMSThread调用