2013-09-24 4 views
0

나는 내 프로그램을 원한다는 것을 보여줄 수 있었다. 문제는 내가 제대로 작동하도록 소켓 연결을 할 수 없다는 것입니다. 그리고 나는 여기서 문제가 어디에 있는지 모른다.자바 서버 - 클라이언트 소켓 문제 (업데이트 됨)

public class TestChat extends Frame { 

public static Panel1 p1; 
public static Panel2 p2; 
public static TestChat tc; 

public TestChat() { 
    super(); 
    setPreferredSize(new Dimension(800, 600)); 
    setLayout(new BorderLayout()); 
    addWindowListener(new WindowAdapter() { 
     public void windowClosing(WindowEvent we) { 
      System.exit(0); 
     } 
    }); 

    p1 = new Panel1(); 
    p2 = new Panel2(); 
    add(p1); 
} 

public static void main(String[] args) { 
    // TODO code application logic here 
    tc = new TestChat(); 
    tc.pack(); 
    tc.setVisible(true); 
    ///* 
    try { 
     TestChat.p2.run(); 
    } catch (IOException ioe) { 
     System.out.println("IO here"); 
    } 
    //*/ 
} 

public void change(int to) { 
    if (to == 1) { 
     tc.remove(p2); 
     tc.add(p1); 
    } 
    if (to == 2) { 
     tc.remove(p1); 
     tc.add(p2); 
    } 
    tc.pack(); 
} 
} 

public class Panel1 extends Panel implements ActionListener{ 

public Button button = new Button("Launch chat"); 

public Panel1() { 
    super(); 
    setLayout(new BorderLayout()); 
    Label label = new Label("Launcher panel here"); 
    add(label); 
    add(button, BorderLayout.SOUTH); 
    button.addActionListener(this); 
} 

@Override 
public void actionPerformed(ActionEvent e) { 
    if (e.getSource() == button) { 
     TestChat.tc.change(2); 
     /* 
     try { 
      TestChat.p2.run(); 
     } catch (IOException ioe) { 
      System.out.println("IO here"); 
     } 
     //*/ 
    } 
} 

} 

public class Panel2 extends Panel implements ActionListener { 

private static final int LOGIN_MAX = 300; 
public static TextArea ta = new TextArea(); 
public static TextField tf = new TextField(); 
public static TextArea logins = new TextArea(); 
public static PrintWriter out = null; 
public static String[] loginList = new String[LOGIN_MAX]; 
public static int loginCount = 0; 
public Panel temp = new Panel(); 
public Button startButton = new Button("Start!"); 
///* 
public String fromServer; 
public BufferedReader in = null; 
public BufferedReader stdIn; 
public Socket kkSocket = null; 
//*/ 

public Panel2() { 
    setLayout(new BorderLayout()); 
    temp.setLayout(new BorderLayout()); 
    ta.setEditable(false); 
    tf.addActionListener(this); 
    startButton.addActionListener(this); 
    logins.setEditable(false); 
    temp.add(ta, BorderLayout.CENTER); 
    temp.add(tf, BorderLayout.SOUTH); 
    add(temp); 
    add(logins, BorderLayout.EAST); 
    add(startButton, BorderLayout.SOUTH); 
} 

//private static void makeLogins() { 
public static void makeLogins() { 
    String userArea = loginList[0] + "\n"; 
    for (int i = 1; i < loginCount; i++) { 
     userArea = userArea + loginList[i] + "\n"; 
    } 
    logins.setText(userArea); 
} 

public void run() throws IOException { 

    kkSocket = null; 

    BufferedReader in = null; 

    try { 
     kkSocket = new Socket("localhost", 4444); 
     out = new PrintWriter(kkSocket.getOutputStream(), true); 
     in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); 
    } catch (UnknownHostException e) { 
     //System.err.println("Can't host to server."); 
     System.out.println("Can't host to server."); 
     System.exit(1); 
    } catch (IOException e) { 
     System.err.println("Couldn't get I/O for the connection to server."); 
     System.exit(1); 
    } 

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); 
    String fromServer; 

    while ((fromServer = in.readLine()) != null) { 
     validate(); 
     if (fromServer.startsWith("cmd_newUser_")) { 
      loginList[loginCount++] = fromServer.substring(12); 
      if (loginCount > 1) { 
       Arrays.sort(loginList, 1, loginCount - 1); 
      } 
      makeLogins(); 
     } else if (fromServer.startsWith("cmd_deleteUser_")) { 
      String tmp = fromServer.substring(15); 
      for (int i = 0; i < loginCount; i++) { 
       if (loginList[i].equals(tmp)) { 
        loginList[i] = "" + ((char) 255); 
        break; 
       } 
      } 
      Arrays.sort(loginList, 1, loginCount); 
      loginCount--; 
      makeLogins(); 
     } else { 
      ta.append(fromServer + "\n"); 
     } 
     if (fromServer.equals("Bye.")) { 
      break; 
     } 
    } 

    out.close(); 
    in.close(); 
    stdIn.close(); 
} 

private void sendStr(PrintWriter out) { 
    if (tf.getText() != "") { 
     out.println(tf.getText()); 
     tf.setText(""); 
    } 
} 

@Override 
public void actionPerformed(ActionEvent e) { 
    if (e.getSource() == tf) { 
     sendStr(out); 
    } else if (e.getSource() == startButton) { 
     System.out.println("I make some actions in the original proj"); 
    } 
} 
} 

이렇게하면 내 프로그램이 연결되고 모든 것이 잘 작동합니다. 하지만 Panel1 클래스에서 버튼을 누르면 (주석 처리 된 호출) 연결을 시작하고 싶습니다. 여기에 문제가 어디서 어떻게 해결할 수 있습니까?

P. 여기에 내 서버 코드가 있습니다. (다만)

public class KKMultiServer extends Frame { 

public static int userCount = 0; 
public static Label users; 
public static KKMultiServerThread[] userList=new KKMultiServerThread[100]; 
public static int writer=0; 
public static int curNum=1; 

public KKMultiServer() { 
    super("Server"); 
    setLayout(new GridLayout(2, 1)); 
    users = new Label("Users online: " + userCount); 
    add(users); 
    setLocation(200, 200); 
    setResizable(false); 
    setMinimumSize(new Dimension(300, 200)); 
    addWindowListener(new WindowAdapter() { 
     public void windowClosing(WindowEvent we) { 
      System.exit(0); 
     } 
    }); 
} 

public static void main(String[] args) throws IOException { 
    ServerSocket serverSocket = null; 
    boolean listening = true; 
    KKMultiServer server = new KKMultiServer(); 
    server.pack(); 
    server.setVisible(true); 

    try { 
     serverSocket = new ServerSocket(4444); 
    } catch (IOException e) { 
     System.err.println("Could not listen on port: 4444."); 
     System.exit(-1); 
    } 

    while (listening) {        
     userList[writer]=new KKMultiServerThread(serverSocket.accept()); 
     System.out.println("Client added!"); 
     userCount++; 
     users.setText("Users online: " + userCount); 
     userList[writer++].start();   


    } 

    serverSocket.close(); 
} 
} 
+0

현재 가지고있는 문제점을 나타내는 최소한의 예를 만드십시오. 이벤트 발송 스레드의 소켓을 사용하려는 것 같습니다. – Joni

+0

작은 문제에서 문제를 해결해야 도움이 될 것입니다. 문제가 발생한 정확한 위치를 파악하고이 특정 문제에 대한 도움을 요청하십시오. 그러면 모든 의문점이 해결 될 때까지 계속하십시오. 지금은 당신을 도울 수 없습니다. – Math

답변

0

나는 당신의 문제를 완전히 이해하고 있는지 잘 모르겠습니다. 그러나 버튼 프레스로 무언가를하고 싶다면 청취자를 사용하고 청취자의 행동을 수행하는 것이 좋습니다. 다음은 버튼을 누를 때 mousePressed() 메서드에서 코드를 실행할 MouseListener의 예입니다.

이것은의 MouseListener 인터페이스 implemenets 작은 개인 클래스 :이 수행해야

Button connectButton = new Button(); 
     connectButton.addMouseListener(new ConnectButtonListener()); 

당신이 당신의 버튼을 만들 : 당신은 다음 버튼에 리스너를 추가해야

private class ConnectButtonListener implements MouseListener{ 

     @Override 
     public void mousePressed(MouseEvent arg0) { 

      //connect to serversocket 

      conectToServer(); 


     } 

    } 

을 . 이 작업이 완료되면 버튼을 클릭하면 MousePressed 메서드가 실행됩니다. 연결 코드는 어디로 가야합니다.

또한 프레임 및 패널을 초기화 할 때 주 스레드가 아닌 스윙 스레드에서 수행해야합니다.

SwingUtilities.invokeLater(new Runnable(){ 

    @Override 
    public void run() { 
      //Initialize GUI here 

    } 

}); 
관련 문제