2016-11-03 1 views
0

Ich habe zwei einfache Java-Programme gemacht: Server-Chat und Client-Chat. Ich sehe keine Fehler in den Codes jeder Java-Datei, aber die Programme hängen, wenn ich versuche, das Client-Programm mit dem Server-Programm zu verbinden. HierJava Chat-Programm (Server und Client) hängt und nichts passiert,

ist der Server-Side-Code:

package com.server; 
import java.io.*; 
import java.net.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class Server extends javax.swing.JFrame { 

private ObjectOutputStream output; 
private ObjectInputStream input; 
private ServerSocket server; 
private Socket connection = null; 

/** 
* Creates new form sever 
*/ 
public Server() { 
    initComponents(); 
} 

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
    // TODO add your handling code here: 
    startRunning(); 
} 

//setup and run the server 
public void startRunning(){ 
    try{ 
     //serversocket(port,queueLength) 
     server = new ServerSocket(6789, 100); 
     while(true){ 
      try{ 
       waitForConnection(); 
       setupStreams(); 
       whileChatting(); 
      }catch(EOFException eofException){ 
       showMessage("\n Server ended the connection!"); 
      }finally{ 
       closeCrap(); 
      } 
     } 
    }catch(IOException ioException){ 
     ioException.printStackTrace(); 
    } 
} 

//wait for connection, then display connection 
private void waitForConnection() throws IOException{ 
    showMessage("Waiting for someone to connect...\n"); 
    connection = server.accept(); 
    showMessage("Now connected to " + connection.getInetAddress()); 
} 

//get stream to send and receive data 
private void setupStreams() throws IOException{ 
    output = new ObjectOutputStream(connection.getOutputStream()); 
    output.flush(); 
    input = new ObjectInputStream(connection.getInputStream()); 
    showMessage("\n Streams are now setup!\n"); 
} 

//during the chat conversation 
private void whileChatting() throws IOException{ 
    String message = "SERVER - You are now connected! "; 
    sendMessage(message); 
    ableToType(true); 
    do{ 
     try{ 
      message = (String) input.readObject(); 
      showMessage("\n" + message); 
     }catch(ClassNotFoundException classNotfoundException){ 
      showMessage("\n idk wtf the user sent!"); 
     } 
    }while(!message.equals("CLIENT - END")); 
} 

//close streams and sockets after chatting 
private void closeCrap(){ 
    showMessage("\n Closing connections...\n"); 
    ableToType(false); 
    try{ 
     output.close(); 
     input.close(); 
     connection.close(); 
    }catch(IOException ioException){ 
     ioException.printStackTrace(); 
    }catch(NullPointerException nullPointerException){ 
     showMessage("You are trying to close something not opened"); 
    } 
} 

//send message to clients 
private void sendMessage(String message){ 
    try{ 
     output.writeObject("SERVER - " + message); 
     output.flush(); 
     showMessage("\nSEVER - " + message); 
    }catch(IOException ioException){ 
     chatWindow.append("\n Error: i cant send that message"); 
    } 
} 

//updates chatWindow 
private void showMessage(final String text){ 
    SwingUtilities.invokeLater(
      new Runnable(){ 
       public void run(){ 
        chatWindow.append(text); 
       } 
      } 
    ); 
} 

//let the user type stuff 
private void ableToType(final boolean tof){ 
    SwingUtilities.invokeLater(
     new Runnable(){ 
      public void run(){ 
       userText.setEditable(tof); 
      } 
     } 
    ); 
} 

    public static void main(String args[]) { 
    /* Set the Nimbus look and feel */ 
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
    * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
    */ 
    try { 
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (ClassNotFoundException ex) { 
     java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 
    //</editor-fold> 



    /* Create and display the form */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new Server().setVisible(true); 
     } 
    }); 
} 

Und hier ist der Client-Seite Code:

package com.client; 

import javax.swing.JOptionPane; 
import java.sql.*; 
import java.io.*; 
import java.net.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class client extends javax.swing.JFrame { 
Connection con; 
int b; 
private ObjectOutputStream output; 
private ObjectInputStream input; 
private String message = ""; 
private String serverIP = "127.0.0.1"; 
private Socket connection; 

public client() { 
    initComponents(); 
} 

private void statusMouseClicked(java.awt.event.MouseEvent evt) {          
    // TODO add your handling code here: 
    startRunning(); 
}         

//start chat system 
public void startRunning(){ 
    try{ 
     connectToServer(); 
     setupStreams(); 
     whileChatting(); 
    }catch(EOFException eofException){ 
     eofException.printStackTrace(); 
     showMessage("\n Client terminated the connection"); 
    }catch(IOException ioException){ 
     ioException.printStackTrace(); 
    }finally{ 
     closeCrap(); 
    } 
} 

//connect to server 
private void connectToServer() throws IOException{ 
    showMessage("\nAttempting connection...\n"); 
    try{ 
     connection = new Socket(InetAddress.getByName(serverIP),6789); 
     showMessage("Connected to: " + connection.getInetAddress().getHostName());    
    }catch(ConnectException connectException){ 
     showMessage("IP not available or port busy"); 
    } 
} 

//streams for seding and receiving 
private void setupStreams() throws IOException{ 
    try{ 
     output = new ObjectOutputStream(connection.getOutputStream()); 
     output.flush(); 
     input = new ObjectInputStream(connection.getInputStream()); 
     showMessage("\n Streams are good to go \n"); 
    }catch(Exception e){ 
     System.out.println("there was error with output or input"); 
    } 

} 

//while chatting with server 
private void whileChatting() throws IOException{ 
    ableToType(true); 
    do{ 
     try{ 
      message = (String) input.readObject(); 
      showMessage("\n" + message); 
      System.out.println(message); 
     }catch(ClassNotFoundException classNotfoundException){ 
      showMessage("\n I dont know what that object is"); 
     }catch(EOFException eofException){ 
      showMessage("\nThere was an error with collecting input "); 
     } 
    }while(!message.equals("SERVER - END")); 
} 

//clos all stuff 
private void closeCrap() { 
    showMessage("\n Closing connection..."); 
    ableToType(false); 
    try{ 
     output.close(); 
     input.close(); 
     connection.close(); 
    }catch(IOException ioException){ 
     ioException.printStackTrace(); 
    } 
} 

//send messages to server 
private void sendMessage(String message){ 
    try{ 
     output.writeObject("CLIENT - " + message); 
     output.flush(); 
     showMessage("\nCLIENT - " + message); 
    }catch(IOException ioException){ 
     chatWindow.append("\n Something went wrong while sending message"); 
    } 
} 

//showMessages 
private void showMessage(final String m){ 
    java.awt.EventQueue.invokeLater(
      new Runnable(){ 
       public void run(){ 
        chatWindow.append(m); 
       } 
      } 
    ); 
} 

//allow typing 
private void ableToType(final boolean tof){ 
    SwingUtilities.invokeLater(
      new Runnable(){ 
       public void run(){ 
        userText.setEditable(tof); 
       } 
      } 
    ); 
} 

//showError 
private void showError(String err){ 
    String errMsg = err; 
    JOptionPane.showMessageDialog(null, errMsg, "Error", JOptionPane.ERROR_MESSAGE); 
} 

public static void main(String args[]) { 
    /* Set the Nimbus look and feel */ 
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
    * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
    */ 
    try { 
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (ClassNotFoundException ex) { 
     java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 

    /* Create and display the form */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new client().setVisible(true); 
     } 
    }); 
} 

Ich werde sehr froh sein, wenn jemand durch gehen könnte und geben Sie mir einige Hinweise, wie man das korrigiert.

+0

Dies kann auch einfach sein, aber haben Sie eine Firewall auf? – DejaVuSansMono

+0

Haben Sie versucht, einen Debugger zu verwenden, um zu sehen, wo genau das Problem liegt? –

+0

Wohin genau beginnt Ihr Server den Port zu hören? Sie haben eine fehlende 'initComponents()' Methode, die Sie uns nicht gegeben haben. – RealSkeptic

Antwort

0

Ich habe Ihren Code versucht. Ich habe kleinere Nacharbeiten gemacht:

  • Bauer startRunning()
  • entfernt invokeLater von showmessage zu nennen. Ich glaube, das hat zu einem Einfrieren der GUI geführt. Es druckte nicht richtig und erstarrte.
  • ein paar andere kleine Dinge.

Und es scheint zu funktionieren ok.

Mein Vorschlag für die Zukunft ist, dass Sie Server/Client von GUI trennen. So können Sie sie einfach leicht gegeneinander testen und es für jede andere Benutzerschnittstelle portabel machen.

Ausgang:

Client: showmessage
Versuch, Verbindung ...

Client: showMessageConnected an: 127.0.0.1
Client: showmessage
Streams sind gut gehen

Client: showMessage
SERVER - SERVER - Sie sind jetzt verbunden!
SERVER - SERVER - Sie sind jetzt verbunden!

Ich füge den Code für Ihre Referenz an.

Server

package com.server; 
import java.io.*; 
import java.net.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class Server extends javax.swing.JFrame { 

    private ObjectOutputStream output; 
    private ObjectInputStream input; 
    private ServerSocket server; 
    private Socket connection = null; 

    /** 
    * Creates new form sever 
    */ 
    public Server() { 
     //initComponents(); 
     startRunning(); 
    } 

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
     // TODO add your handling code here: 
     startRunning(); 
    } 

    //setup and run the server 
    public void startRunning(){ 
     try{ 
      //serversocket(port,queueLength) 
      server = new ServerSocket(6789, 100); 
      while(true){ 
       try{ 
        waitForConnection(); 
        setupStreams(); 
        whileChatting(); 
       }catch(EOFException eofException){ 
        showMessage("\n Server ended the connection!"); 
       }finally{ 
        closeCrap(); 
       } 
      } 
     }catch(IOException ioException){ 
      ioException.printStackTrace(); 
     } 
    } 

    //wait for connection, then display connection 
    private void waitForConnection() throws IOException{ 
     showMessage("Waiting for someone to connect...\n"); 
     connection = server.accept(); 
     showMessage("Now connected to " + connection.getInetAddress()); 
    } 

    //get stream to send and receive data 
    private void setupStreams() throws IOException{ 
     output = new ObjectOutputStream(connection.getOutputStream()); 
     output.flush(); 
     input = new ObjectInputStream(connection.getInputStream()); 
     showMessage("\n Streams are now setup!\n"); 
    } 

    //during the chat conversation 
    private void whileChatting() throws IOException{ 
     String message = "SERVER - You are now connected! "; 
     sendMessage(message); 
     ableToType(true); 
     do{ 
      try{ 
       message = (String) input.readObject(); 
       showMessage("\n" + message); 
      }catch(ClassNotFoundException classNotfoundException){ 
       showMessage("\n idk wtf the user sent!"); 
      } 
     }while(!message.equals("CLIENT - END")); 
    } 

    //close streams and sockets after chatting 
    private void closeCrap(){ 
     showMessage("\n Closing connections...\n"); 
     ableToType(false); 
     try{ 
      output.close(); 
      input.close(); 
      connection.close(); 
     }catch(IOException ioException){ 
      ioException.printStackTrace(); 
     }catch(NullPointerException nullPointerException){ 
      showMessage("You are trying to close something not opened"); 
     } 
    } 

    //send message to clients 
    private void sendMessage(String message){ 
     try{ 
      output.writeObject("SERVER - " + message); 
      output.flush(); 
      showMessage("\nSEVER - " + message); 
     }catch(IOException ioException){ 
      System.out.println("\n Error: i cant send that message"); 
    //  chatWindow.append("\n Error: i cant send that message"); 
     } 
    } 

    //updates chatWindow 
    private void showMessage(final String text){ 
     // INVOKE LATER REMOVED. 
     System.out.println(text);; 
    } 

    //let the user type stuff 
    private void ableToType(final boolean tof){ 
     // INVOKE LATER REMOVED. 
        System.out.println("userText -> setEditable off"); 
    } 

    public static void main(String args[]) { 
     /* Set the Nimbus look and feel */ 
     //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
     /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */ 
     try { 
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
       if ("Nimbus".equals(info.getName())) { 
        javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
        break; 
       } 
      } 
     } catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     //</editor-fold> 
     //</editor-fold> 



     /* Create and display the form */ 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new Server().setVisible(true); 
      } 
     }); 
    } 
} 

Auftraggeber:

package com.client; 

import javax.swing.JOptionPane; 
import java.sql.*; 
import java.io.*; 
import java.net.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class client extends javax.swing.JFrame { 
    Connection con; 
    int b; 
    private ObjectOutputStream output; 
    private ObjectInputStream input; 
    private String message = ""; 
    private String serverIP = "127.0.0.1"; 
    private Socket connection; 

    public client() { 
     //initComponents(); 
     startRunning(); 
    } 

    private void statusMouseClicked(java.awt.event.MouseEvent evt) {          
     // TODO add your handling code here: 
     startRunning(); 
    }         

    //start chat system 
    public void startRunning(){ 
     try{ 
      connectToServer(); 
      setupStreams(); 
      whileChatting(); 
     }catch(EOFException eofException){ 
      eofException.printStackTrace(); 
      showMessage("\n Client terminated the connection"); 
     }catch(IOException ioException){ 
      ioException.printStackTrace(); 
     }finally{ 
      closeCrap(); 
     } 
    } 

    //connect to server 
    private void connectToServer() throws IOException{ 
     showMessage("\nAttempting connection...\n"); 
     try{ 
      connection = new Socket(InetAddress.getByName(serverIP),6789); 
      showMessage("Connected to: " + connection.getInetAddress().getHostName());    
     }catch(ConnectException connectException){ 
      showMessage("IP not available or port busy"); 
     } 
    } 

    //streams for seding and receiving 
    private void setupStreams() throws IOException{ 
     try{ 
      output = new ObjectOutputStream(connection.getOutputStream()); 
      output.flush(); 
      input = new ObjectInputStream(connection.getInputStream()); 
      showMessage("\n Streams are good to go \n"); 
     }catch(Exception e){ 
      System.out.println("there was error with output or input"); 
      e.printStackTrace(); 
     } 

    } 

    //while chatting with server 
    private void whileChatting() throws IOException{ 
     ableToType(true); 
     do{ 
      try{ 
       message = (String) input.readObject(); 
       showMessage("\n" + message); 
       System.out.println(message); 
      }catch(ClassNotFoundException classNotfoundException){ 
       showMessage("\n I dont know what that object is"); 
      }catch(EOFException eofException){ 
       showMessage("\nThere was an error with collecting input "); 
      } 
     }while(!message.equals("SERVER - END")); 
    } 

    //clos all stuff 
    private void closeCrap() { 
     showMessage("\n Closing connection..."); 
     ableToType(false); 
     try{ 
      output.close(); 
      input.close(); 
      connection.close(); 
     }catch(IOException ioException){ 
      ioException.printStackTrace(); 
     } 
    } 

    //send messages to server 
    private void sendMessage(String message){ 
     try{ 
      output.writeObject("CLIENT - " + message); 
      output.flush(); 
      showMessage("\nCLIENT - " + message); 
     }catch(IOException ioException){ 
      // chatWindow.append("\n Something went wrong while sending message"); 
     } 
    } 

    //showMessages 
    private void showMessage(final String m){ 
     // INVOKE LATER REMOVED. 
         System.out.println("client: showMessage" + m); 
    } 

    //allow typing 
    private void ableToType(final boolean tof){ 
     // INVOKE LATER REMOVED. 
     System.out.println("userText.setEditable: " + tof); 
    } 

    //showError 
    private void showError(String err){ 
     String errMsg = err; 
     JOptionPane.showMessageDialog(null, errMsg, "Error", JOptionPane.ERROR_MESSAGE); 
    } 

    public static void main(String args[]) { 
     /* Set the Nimbus look and feel */ 
     //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
     /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */ 
     try { 
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
       if ("Nimbus".equals(info.getName())) { 
        javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
        break; 
       } 
      } 
     } catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     //</editor-fold> 

     /* Create and display the form */ 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new client().setVisible(true); 
      } 
     }); 
    } 
} 
+0

Danke für Ihre Eingabe Vito, in dem Code, den ich den Client und den Server veröffentlicht haben, sind alle in separaten Paketen.Das Programm friert ein, wenn eine Verbindung besteht. Aber wenn die Verbindung getrennt wird, werden die Inhalte in das ChatWindow gedruckt. Ihr Ansatz funktioniert einwandfrei, aber der Server kann keine Nachrichten an den Client senden und umgekehrt. – gray4webs

+0

Ich bin mir nicht sicher, auf welches Problem Sie sich beziehen. Ich sehe, dass die Nachrichten übergeben und gedruckt werden. Mein Vorschlag ist, dass Sie invokeLater() Zeug entfernen. Es verursacht das Einfrieren. Ersetzen Sie alles, was im Chat ist, mit der Konsole. Es funktioniert an meinem Ende. Lass es mich wissen, wenn es geholfen hat. –

+0

danke .... werde es versuchen – gray4webs