2017-05-14 12 views
-3

分散マルチプレイヤーゲームを作成しようとしています。このアーキテクチャーは、古典的なサーバー・クライアントのアーキテクチャーであり、ソケットを使用して通信します。私は、それぞれのクライアントをそれぞれのソケットを介して異なるスレッドに一致させるために、サーバにスレッドプールを作成したいと思うでしょう。問題は、execute(Runnable)メソッドは一度しか動作しないということです!これは、コードの一部である:Javaスレッドプールexecturは一度実行(実行可能)メソッドを実行します

サーバー:実行する

public class Server extends ThreadPoolExecutor{ 
    Server() throws IOException{ 
    super(MIN_POOL_SIZE, MAX_POOL_SIZE, TIME_ALIVE, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(MAX_POOL_SIZE)); 
    listener=new ServerSocket(PORT_NO); 
    listener.setSoTimeout(SERVER_TIMEOUT); 
    clients=new ArrayList<ClientConnection>(); 
    System.out.println("Listening on port "+PORT_NO); 
    } 

void runServer(){ 
    Socket socket; 
    ClientConnection connection; 
    try{ 
     while(true){ 
     socket=listener.accept(); 
     System.out.println("client accettato"); 
     connection=new ClientConnection(socket, this); 
     System.out.println("creata la connection"); 
     try{ 
      execute(connection); 
      //clients.add(connection); 
      // System.out.println("Accepted connection"); 
      // connection.send("Welcome!"); 
     } 
     catch(RejectedExecutionException e){ 
      //connection.send("Server is full!!!"); 
      socket.close(); 
     } 
     } 
    } 
    catch (IOException ioe){ 
     try{listener.close();}catch (IOException e){ 
     e.printStackTrace(); 
     } 
     System.out.println("Time to join the match expired"); 
     //init(); 
    } 
    } 
} 

のRunnable:

public class ClientConnection extends Player implements Runnable{ 
    // private static final boolean BLACK=false; 
    // private static final boolean WHITE=true; 
    // private int ammo; 
    // private boolean team; 

    private volatile BufferedReader br; 
    private volatile PrintWriter pw; 
    private volatile Server server; 
    private volatile Socket socket; 

    public ClientConnection(Socket s, Server srv) throws IOException{ 
    super(10+(int)Math.random()*30, true); 
    socket=s; 
    server=srv; 
    br = new BufferedReader(new InputStreamReader(s.getInputStream())); 
    pw = new PrintWriter(s.getOutputStream(), true); 
    System.out.println("costruzione nuovo socket"); 
    } 

    @Override 
    public void run(){ 
    System.out.println("run execution"); 
    while(true); 
    } 

    public void send(String message){ 
    pw.println(message); 
    } 
} 

問題は、実行中の線「ランの実行」()メソッドが一度に印刷されていることです。私は何が問題なのか分かりません。私を助けることができる人は誰ですか? ありがとうございます!

+1

あなたはどれくらいの期待をしていますか?実行され、スレッドは無限ループに入り、while(真)は何もしません。 – Antoniossss

答えて

1
System.out.println("run execution"); 
while(true); 

これは問題です。なぜコンソールに印刷した後、無限ループに行くのですか?私はあなたがprintステートメントを無制限に実行したいと思っています。このようなことをしたいのですか?

while (true) { 
     System.out.println("run execution"); 
} 
関連する問題