2014-09-22 3 views
0

나는 서버/클라이언트를 만들고 있는데 문제가있는 것 같다. 버튼을 클릭하면 연결할 수 없습니다. 제발 도와주세요. 내가 잘못했는지 확신 할 수 없습니다. 코드를 수정하여 자유롭게 수정 한 다음 제발 의견을 말하십시오. 연결 버튼과 보내기 버튼이 있습니다. 나는 그것이 강조 표시된 코드와 관련이 있다고 생각하지만 그것은 무엇이든 될 수있다. 나는 이것이 매우 구체적인 것은 아니라는 것을 알고 있지만 기본적으로 코드를 heres하고 그것은 작동하지 않는다. 나는 연결할 수 없다. 도와주세요!java에서 서버 및 클라이언트를 만드는 방법은 무엇입니까?

클라이언트

public class chat_client extends javax.swing.JFrame { 


    String username; 
    Socket sock; 
    BufferedReader reader; 
    PrintWriter writer; 
    ArrayList<String>userList = new ArrayList(); 
    Boolean isConnected = false; 



    public chat_client() { 
     initComponents(); 
     getContentPane().setBackground(Color.white); 
     this.setIconImage(new ImageIcon(getClass() 
       .getResource("dogeIcon.jpg")).getImage()); 
     this.setLocationRelativeTo(null); 
    } 

    public class IncomingReader implements Runnable{ 

     public void run(){ 
      String stream; 
      String[] data; 
      String done = "Done", connect = "Connect", 
        disconnect = "Disconnect", chat = "Chat"; 

      try { 
       while ((stream = reader.readLine()) != null){} 

        data = stream.split("^"); 

        if (data[2].equals(chat)){ 
         txtChat.append(data[0] + ":" + data[1] + "\n"); 

        } else if (data[2].equals(connect)){ 
         txtChat.removeAll(); 
         userAdd(data[0]); 

        } else if (data[2].equals(disconnect)){ 
         userRemove(data[0]); 

        } else if (data[2].equals(done)){ 
         userList.setText(""); 
         writeUsers(); 

        } 

      } catch(Exception ex){ 
      } 
     } 
    } 

    public void ListenThread(){ 
     Thread IncomingReader = new Thread(new IncomingReader()); 
     IncomingReader.start(); 
    } 

    public void userAdd(String data){ 
     userList.add(data); 
    } 

    public void userRemove(String data){ 
     txtChat.append(data + " has disconnected \n"); 
    } 

    public void writeUsers(){ 
     String[] tempList = new String[(userList.size())]; 
     userList.toArray(tempList); 
     for (String token:tempList){ 
      userList.append(token + "\n"); 
     } 
    } 

    public void sendDisconnect(){ 
     String bye = (username + "^ ^Disconnected"); 
     try{ 
      writer.println(bye); 
      writer.flush(); 

     } catch(Exception e){ 
      txtChat.append("Could Not Send Disconnect Message \n"); 
     } 
    } 

    public void Disconnect(){ 
     try{ 
      txtChat.append("Disconnected\n"); 
      sock.close(); 
     } catch(Exception ex){ 
      txtChat.append("Failed to disconnect\n"); 
     } 
     isConnected = false; 
     txtUser.setEditable(true); 
     userList.setText(""); 
    } 

***private void connectActionPerformed(java.awt.event.ActionEvent evt) { 
    if (isConnected == false){ 
     username = txtUser.getText(); 
     txtUser.setEditable(false); 

     try{ 
      sock = new Socket("localhost", 1023); 
      InputStreamReader streamreader 
        = new InputStreamReader(sock.getInputStream()); 
      reader = new BufferedReader(streamreader); 
      writer = new PrintWriter(sock.getOutputStream()); 
      writer.println(username + "^has connected.^Connect"); 
      writer.flush(); 
      isConnected = true; 


     } catch(Exception ex){ 
      txtChat.append("Cannot Connect! Try Again\n"); 
      txtUser.setEditable(true); 
     } 
     ListenThread(); 
    } else if (isConnected == true){ 
     txtChat.append("You is connected bra\n"); 
    } 
}***    

은 (여기-끝 문제/하이라이트 부분)

private void btn_SendActionPerformed(java.awt.event.ActionEvent evt) {  

    String nothing = ""; 
    if ((txtMsg.getText()).equals(nothing)){ 

     txtMsg.setText(""); 

     txtMsg.requestFocus(); 

    } else { 
     try{ 
      writer.println(username + "^" + txtMsg.getText() + "^" 
        + "Chat"); 
      writer.flush(); 
     } catch (Exception ex){ 
      txtChat.append("Message was not sent\n"); 
     } 
     txtMsg.setText(""); 
     txtMsg.requestFocus(); 

    } 
+0

"강조 표시된 코드와 관련이 있다고 생각합니다."강조 표시된 코드가 무엇인지 지정할 수 있습니까? – TNT

+0

편집 했으므로 이제 강조 표시된 부분이 표시됩니다. – greg

+0

버튼을 클릭하면 어떻게됩니까? 오류 메시지가 나타 납니까? 전혀? – TNT

답변

0
(이것은 내가 문제라고 생각 강조 표시된 부분)

몇 가지 사항 :

  1. 연결이 거부되므로 java.net.ConnectionException (아래 참조)이 표시됩니다. 연결하려는 서버가 실행 중이 아니거나 서버가 클라이언트 연결을 허용하지 않았거나 클라이언트가 서버에 액세스 할 수 없거나 잘못된 포트 번호에 연결했기 때문일 수 있습니다.

  2. Exception을 직접 잡는 것은 일반적으로 코딩 방법이 좋지 않습니다. 던져 질 수있는 다양한 예외 (이 경우 IOException)에 해당하는 가장 구체적인 예외를 잡거나 원하는 각각의 가능한 예외를 catch하려고합니다. 가장 일반적인 예외 앞에 가장 구체적인 예외를 잡아서 마스크가 적용되지 않도록합니다. 또한 Throwable 클래스의 getMessage() 메서드를 사용하면 예외가 throw되는 이유를 파악할 수 있습니다. 예를 들어 : 물론

    } catch (java.net.ConnectException ex) { 
        System.err.println("ConnectException: " + ex.getMessage()); // May return "Connection refused", "Connection timed out", "Connection reset", etc. 
    } catch (java.rmi.UnknownHostException ex) { 
        System.err.println("UnknownHostException: " + ex.getMessage()); // Returns the name of the host you were attempting to connect to 
    } catch (...) { 
        // code here 
    } catch (java.io.IOException ex) { 
        System.err.println("IOException: " + ex.getMessage()); // May return a problem with the BufferedReader or InputStreamReader or PrintWriter 
    } 
    

    catch 절에 문이 원하는대로 수정할 수 있습니다.

관련 문제