2013-11-25 2 views
1

여러 클라이언트를 허용하는 서버를 만들려고합니다. 하나의 클라이언트와 연결할 수 있지만 두 개로는 연결할 수 없습니다. 두 개의 클라이언트를 서버에 연결하려고하면 메인 메소드에 두 개의 클라이언트 오브젝트와 한 개의 서버를 작성합니다.여러 클라이언트가있는 서버에 연결

public class DraughtsSever extends JFrame{ 

JPanel panel; 
JTextArea gamesList; 
ServerSocket draughtsSS; 
JScrollPane scroll; 
Socket s; 
int i = 0; 

DraughtsSever(){ 
    panel = new JPanel(); 
    panel.setPreferredSize(new Dimension(350,350)); 
    gamesList = new JTextArea(); 
    //scroll.setPreferredSize(new Dimension(350,350)); 
    gamesList.setPreferredSize(new Dimension(300,300)); 
    //scroll.add(GamesList); 
    //scroll = new JScrollPane(GamesList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 
    //panel.add(scroll); 
    this.add(panel); 
    panel.add(gamesList); 
    this.setSize(400,400); 
    this.setVisible(true); 
    this.setTitle("Draughts Server"); 

    panel.add(gamesList); 
    allowConnections(); 
} 

public void allowConnections(){ 
    gamesList.append("Server listening on port 50000..."); 
    try{ 
     while(true){    
      draughtsSS = new ServerSocket(50000); 
      //s = draughtsSS.accept(); 
      new Thread(new TestT(draughtsSS.accept())).start(); 
      //t.start(); 
     } 
    } 
    catch(IOException e){ 
     System.out.println("Error :"+e.getMessage()); 
    } 
} 


class TestT implements Runnable{ 

    Socket s; 

    TestT(Socket s){ 
     this.s = s; 
    } 

    public void run(){ 
     try{ 
      PrintWriter out = new PrintWriter(s.getOutputStream()); 
      Scanner in = new Scanner(s.getInputStream()); 
      gamesList.append("\n"+s.getInetAddress().toString() +" has connected."); 
      JOptionPane.showMessageDialog(new JFrame(), "Successfully connected"); 
      out.println("hello"); 
      System.out.println(s.getInetAddress().toString() +" has connected."); 
     } 
     catch(IOException e){ 

     } 
    } 
} 

} 여기

내가 서버

private void setupConnection(String serverIP, String port){ 
    int portInt = Integer.parseInt(port); 
    try{ 
     InetAddress IP = InetAddress.getByName(serverIP); 
     int intPort = Integer.parseInt(port); 
     Socket clientSocket = new Socket(IP,intPort); 
     JOptionPane.showMessageDialog(new JFrame(), "Successfully connected to Server"); 
     PrintWriter out = new PrintWriter(clientSocket.getOutputStream()); 
     Scanner in = new Scanner(clientSocket.getInputStream()); 
     //in. 
    } 
    catch(Exception e){ 
     System.out.println("ErrorC :" +e.getMessage()); 
    } 
} 

} }

답변

2

I에 연결하는 데 사용하는 클라이언트의 방법은 다음은 서버의 코드는 한 번만 서버 소켓을 생성해야한다고 생각하면 while 루프 외부로 이동하십시오.

draughtsSS = new ServerSocket(50000); 

당신 보관할 필요가없는 다시 만드는 당신이 onec 그것을 받아 들일 필요는 네를

draughtsSS.accept() 
+0

를 호출 할 때 클라이언트가 소켓을 사용하여, 그들은 자동으로 다른 소켓에 이동 얻을 연결할 때 때문입니다. – Serafins

관련 문제