2013-02-21 3 views
0

자바에서 ArrayList를 사용하는 데 문제가 있습니다. 그 클래스에 값을주고, arrayList에 해당 객체를 추가 한 다음 이미 사용 된 객체에 "new"라는 키워드를 사용하여 새로운 클래스 객체를 만들고 있습니다. 그것은 다른 데이터를 가지고 있지만 변경되지 않은 데이터이지만 이전에 설정되었던 데이터는 여전히 설정되어 있습니까? 여기 새로운 개체가 실제로 새로운 것은 아닙니까?

내 코드입니다

private static ArrayList<PongServerThread> games = new ArrayList<PongServerThread>(); 
private static int players = 0; 
private static PongServerThread game; 

public static void main(String args[]) throws IOException, InterruptedException 
{ 
    while(true) 
    { 
     System.out.println("Start of Loop"); 

     if(game.getPlayers() == 0) 
     { 
      System.out.println("Waiting for players"); 
     } 
     if(game.getPlayers() == 2) 
     { 
      System.out.println("Game Added"); 
      games.add(game); 
      games.get((games.size())-1).start(); 
      game.setPlayers(0); 
     } 

     game = new PongServerThread(); 
    } 
} 

이 코드는 잘 작동하지만 두 클라이언트가 연결 한 후 내 PongServerThread에, 메인 스레드를 시작하고 새로운 PongServerThread 객체는 그래서 2 개를 시작해야 클라이언트는 해당 스레드에 연결하지만 일어나고있는 것은,이 클라이언트 한 번 스레드 시작, 여기

game = new PongServerThread(); 

이 다시 생성됩니다 만, 새로운 클라이언트가 연결되면 첫 번째 인수 할 새로운 스레드 수 클라이언트에 연결하고 다른 클라이언트가 연결되면 아케 등 등 2 클라이언트를 통해, 그래서 무슨 일이 일어나고은

game = new PongServerThread(); 

정말 새로운 PongServerThread을하지 않는다에 대한 행이 나는이 고정은 어떻게하는 것입니까? 여기 두 클라이언트가 연결 한 콘솔 출력은 --- 다음, 내 서버 생성자

public PongServerThread() throws IOException, InterruptedException 
{ 

    //Setup 
      super("PongServerThread"); 
      setupPong(); 
      boolean listen = false; 
      boolean playing = false; 
      System.out.println(rtnInfo()); 


      System.out.println("Server started"); 
      //Create a serverSocket to listen on 
      ServerSocket serverSocket = null; 

      try 
      { 
       serverSocket = new ServerSocket(port); 
       listen = true; 
       System.out.println("Server was setup and will try to create a socket"); 
      } 
      catch(IOException e) 
      { 
       System.err.println("Could not listen on port:" + port); 
       System.exit(1); 
      } 

      while(listen) 
      { 
       /*PongPlayerThread player1 = */ 
       players[idPlayer] = new PongPlayerThread(serverSocket.accept(), idPlayer, rtnInfo()); 
       players[idPlayer].start(); 
       System.out.println("Client Connected with ID:" + idPlayer); 
       players[0].passData(rtnInfo()); 
       idPlayer++;  
       if(idPlayer > 1) 
       { 
        listen = false; 
        playing = true; 
       } 
      } 

      int timer = 0; 
      System.out.println("Server Closed"); 
      serverSocket.close(); 

} 

여기

을 ----- 1 개 커넥트 라이언에 대한

Start of Loop 
Waiting for players 
Pong 
400.0:301.0:60.0:300.0:740.0:300.0 
Server started 
Server was setup and will try to create a socket 
Client Connected with ID:0 
Checking readLine value 
Client Connected with ID:1 
Start of Loop 
Game Added 
Pong 
400.0:300.0:60.0:300.0:740.0:300.0 
Server started 
Server was setup and will try to create a socket 
Checking readLine value 
Client Connected with ID:0 
Checking readLine value 

업데이트입니다 업데이트 ---

방금 ​​변수 중 일부를 정적으로 선언했다는 것을 알았습니다. 그리고 이것은 아마도 오류가 발생하는 이유 일 수 있습니다. 그러나 이제는 서버를 실행하려고 할 때가되었습니다.

class Main 
{ 
// Variable 
private ArrayList<PongServerThread> games = new ArrayList<PongServerThread>(); 
private int players = 0; 
private PongServerThread game; 

public void main(String args[]) throws IOException, InterruptedException 
{ 
    //PongServerThread game = new PongServerThread(); 
    /*if(pt.getPlayers() == 2) 
    { 
     System.out.println("Started"); 
     pt.start(); 
    }*/ 

    PongServerThread game = new PongServerThread(); 
     while(true) 
     { 
      games.add(game); 
      System.out.println("Game Added"); 
      game.start(); 

      game = new PongServerThread(); 
     } 
    /*System.out.println("Pong"); 
    PongModel model = new PongModel(); 
    PongView view = new PongView(); 
         new PongController(model, view); 

    model.addObserver(view);  // Add observer to the model 

    view.setVisible(true);   // Display Screen 
    model.makeActiveObject();  // Start play*/ 
} 
} 

코드

가 나는 것을 얻는 것이 왜
Could not get Input/Output from server 

사람이 알겠습니까

이 오류를 얻을? 필요한 경우 더 많은 코드를 붙여 넣을 수 있습니다. 스레드를 시작하기 위해

+0

그래서 ... PongServerThread의 생성자는 어떻게 생겼습니까? –

+0

는 pong 게임을위한 모든 것을 설정하므로 소켓을 설정하고 두 사람이 연결될 때까지 클라이언트를 청취합니다. 연결되어있을 때 청취는 false가됩니다. – Canvas

+0

'키워드 사용 "new"를 이미 사용 된 객체에 추가합니다. 번역 부탁드립니다. – EJP

답변

0

때문에 2 명의 플레이어가있는 게임이있을 때 주 기능을 상당히 단순화 할 수 있습니다.

{ 
    PongServerThread game = new PongServerThread(); 
    while(true) 
    { 
     games.add(game); 
     System.out.println("Game Added"); 
     game.start(); 

     game = new PongServerThread(); 
    } 
} 

Line game.setPlayers(0);은 매우 이상합니다. 왜 게임을 2 명의 플레이어와 막 시작했는지, 게임의 플레이어 수를 0으로 설정해야하는 이유입니다.

편집 :

만약 내가 제대로 이해하고는 setPlaysers(0) 전화 세트는 정적 변수 players에 제로.이것이 제 3의 클라이언트가 ID = 0을 얻는 이유입니다. 그리고 네 번째 클라이언트 ID = 1; 아마도 '덮어 쓰기'처럼 보일 것입니다.

따라서 game.setPlayers(0);을 제거하면 모든 플레이어가 고유 한 식별자를 갖게됩니다.

+0

이 정확한지 만 새 게임이 만들어 지길 원합니다. 두 명의 사용자가 연결되면 두 명의 사용자가 연결되면 새 서버가 만들어 지지만 새 클라이언트가 연결을 시도하면 아무 일도 일어나지 않습니다. 즉, pongServer가 2 명이되어 더 이상 듣지 않을 것입니다. PongServerThread의 새로운 인스턴스를 만들고 기존 인스턴스를 작성하지 않으려 고합니다. – Canvas

+0

@Canvas : 코드에 덮어 쓰기가 표시되지 않습니다. 'game = new PongServerThread();'줄은 기존 게임 객체를 덮어 쓰지 않습니다. – SKi

+0

그러면 어떻게 할 것입니까? 내가 일어나려고하는 것은 새로운 pongServerThread가 만들어지고, 두 클라이언트가 연결되고 두 클라이언트가 연결되면 pongServerThread가 시작되고 새로운 pongServerThread가 만들어 질 때까지 기다릴 것입니다. 연결할 두 개의 다른 클라이언트, 등등. – Canvas

1

, 당신은 예를 들어, 호출해야합니다 : 일반적으로

game.start(); 

, Runnable을 구현하는 것이 바람직하다, 다음 말 : PongServerThread는()는 반환

Runnable myThread = ...; 
new Thread(myThread).start(); 
+2

그는 생성자에서이를 호출 할 수 있습니다. 우리는 모른다. 나는 이것이 주 스레드에서 읽기/쓰기를하지 않기 때문에 가능성이 있다고 생각합니다. –

+0

사실, 나는 그것에 대해 생각하지 않았다, 고마워! 귀하의 의견을 Upvoted. :) –

+0

games.get ((games.size()) - 1) .start(); 라인이 스레드를 시작, 내 탁구 게임 업데이 트가 잘 작동합니다. – Canvas

관련 문제