2014-11-24 134 views
0

我正在爲一個類的聊天客戶端工作,並遇到一些我似乎無法找到的問題。在ChatWindowEchoServer中,所有的系統打印行都工作正常,除了一個,它永遠不會「服務器響應」。每次它嘗試發送到服務器時,它都會按照正確的方式打印出應該發送的內容,但服務器從不接收任何內容。有沒有人有任何想法,我在這裏遇到什麼?請注意,我沒有從編譯器或運行時收到任何錯誤。Java聊天客戶端和服務器沒有收到

還是新的到stackoverflow,請讓我知道,如果有什麼我可以添加到這裏來幫助。

編輯1:仍然有相同的問題,但在EchoServer中的循環中添加以修復連接到客戶端後立即關閉服務器的錯誤。

編輯2:我發現套接字正在關閉我,這就是爲什麼服務器斷開連接,我現在無法弄清楚爲什麼套接字可能會關閉。我的斷點,我在進入新創建的線程後立即在構造函數中找到一個封閉的套接字。

編輯3:進行了必要的修理,代碼現在正常工作。

// Simple server to receive communication from a client on the same computer and echo it back 
public class EchoServer { 
    public static void main(String[] args) throws IOException { 
     try (ServerSocket s = new ServerSocket(4688)) { 
     // wait for client connection 
      try (Socket incoming = s.accept()) { 
      System.out.println("client connected"); 
      try (Scanner in = new Scanner(incoming.getInputStream())) { 
       PrintWriter out = new PrintWriter(incoming.getOutputStream()); 
       out.println("Hello! Enter BYE to exit."); 
       out.flush(); 

       System.out.println("sent message to client"); 

       // echo client input 
       boolean done = false; 
       while (true) { 
        while (!done && in.hasNextLine()) { 
         String line = in.nextLine(); 
         System.out.println(line); 
         out.println("Echo: " + line); 
         out.flush(); 
         if (line.trim().equals("BYE")) done = true; 
        } 
        if(done) break; 
       } 
      } 
     } 
     } 
    } 
} 

// Client main class. runs next class 
public class ChatProgram { 
    public static void main(String[] args){ 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        JFrame frame = new ChatWindow(); 
        frame.setTitle("Chat Program"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setVisible(true); 
       } catch (IOException ex) { 
        Logger.getLogger(ChatProgram.class.getName()).log(Level.SEVERE, null, ex); 
       } 
      } 
     }); 
    } 
} 



// accepts user input from a textField when button is pressed. 
// gives it to the server and prints it in it's own textArea 
// 
public class ChatWindow extends JFrame { 
    private String username = ""; 
    private Scanner in; 
    private PrintWriter out; 
    private Socket s; 
    public ChatWindow() throws IOException { 
     initComponents(); // this initializes the gui 
      try { 
      s = new Socket("localhost", 4688); 
      System.out.println("Connected to server"); 
      in = new Scanner(s.getInputStream()); 
      out = new PrintWriter(s.getOutputStream()); 
      class PollServer implements Runnable { 
       @Override 
       public void run(){ 
        while(true){ 
         if(in.hasNextLine()){ 
          System.out.println("server responded"); 
          String input = in.nextLine(); 
          PrintToWindow(input); 
         } 
        } 
       } 
      } 
      catch(IOException io) { 
      //I'll do something with this 
      } 
      Thread t1 = new Thread(new PollServer()); 
      t1.start(); 
     } 
    } 

    // Connect will be used later 
    public void Connect() { 
     SendToServer("connect " + username); 
    } 

    // Disconnect will be used later 
    public void Disconnect() { 
     SendToServer("Disconnect " + username); 
    } 

    // Handles all outbound messages to the server 
    public void SendToServer(String clientOut) { 
     out.println(clientOut); 
     PrintToWindow(clientOut); 
     System.out.println("sending to server: " + clientOut); // Program hits this and prints  correctly every time 
     out.flush(); 
    } 

    // Handles adding anything to the client's textArea. Will be implementing Synchronized later 
    public void PrintToWindow(String clientIn) { 
     textArea.append(clientIn + "\n"); 
    } 
} 
+0

我不前儘可能確保負面影響(儘管JVM無論如何優化它都不會令我感到驚訝),但是您不需要像這樣在構造函數中定義「PollServer」類。如果你將它提取到一個單獨的類,它會使代碼更清潔。 – 2014-11-24 02:07:57

+0

不幸的是只有那裏作爲我的項目的需求 – 2014-11-24 02:15:50

+0

然後採取不同的課程。那太糟了。 – csmckelvey 2014-11-24 02:34:59

回答

0

修復了這個問題。結果發生了什麼只是我只是在構造函數中本地聲明瞭套接字。所以一旦構造函數完成,儘管我的全局「in」和「out」變量,套接字消失了。我已修復代碼以包含更改,並且它現在可以正常工作

0

很好,您已解決了您的問題。在這裏,我爲你開發了一個簡單的,可能會幫助你很多。

客戶端類

public class Client { 

    Socket s; 
    int port = 7777; 
    DataOutputStream dos; 
    DataInputStream dis; 
    String IPAddress = "localhost"; 
    String title = "Client"; 

    public Client() { 
     try { 
      s = new Socket(IPAddress, port); 
      dos = new DataOutputStream(s.getOutputStream()); 
      dis = new DataInputStream(s.getInputStream()); 
      new Window(title, dos, dis); 
     } catch (Exception ex) { 
     } 
    } 

    public static void main(String[] args) { 
     new Client(); 
    } 
} 

服務器類

public class Server { 

    ServerSocket ss; 
    Socket s; 
    int port = 7777; 
    DataOutputStream dos; 
    DataInputStream dis; 
    String title = "Server"; 

    public Server() { 
     try { 
      ss = new ServerSocket(port); 
      System.out.println("Server is listenning for incoming connection..."); 
      s = ss.accept(); 
      dos = new DataOutputStream(s.getOutputStream()); 
      dis = new DataInputStream(s.getInputStream()); 
      new Window(title, dos, dis); 
     } catch (Exception ex) { 
     } 
    } 

    public static void main(String[] args) { 
     new Server(); 
    } 
} 

公共窗口類

public class Window extends JFrame { 

    JTextArea display = new JTextArea(); 
    JScrollPane jsp = new JScrollPane(display); 
    JTextField write = new JTextField(); 
    String msg; 
    DataOutputStream dos; 
    DataInputStream dis; 

    public Window(String title, DataOutputStream dos, DataInputStream dis) { 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.dos = dos; 
     this.dis = dis; 
     add(jsp, BorderLayout.CENTER); 
     add(write, BorderLayout.SOUTH); 
     setTitle(title); 
     setSize(300, 200); 
     setVisible(true); 
     write.addKeyListener(new KeyAdapter() { 

      @Override 
      public void keyPressed(KeyEvent ke) { 
       if (ke.getKeyCode() == KeyEvent.VK_ENTER) { 
        msg = write.getText(); 
        write.setText(""); 
        appendToDisplay(title + " : " + msg); 
        try { 
         dos.writeUTF(title + " : "+ msg); 
        } catch (Exception ex) { 
         System.out.println(ex.getMessage()); 
         appendToDisplay("Cannot write to ..."); 
        } 
       } 
      } 
     }); 
     new Thread() { 
      String msgRead; 

      @Override 
      public void run() { 
       while (true) { 
        try { 
         msgRead = dis.readUTF(); 
         appendToDisplay(msgRead); 
        } catch (Exception ex) { 
         System.out.println(ex.getMessage()); 
         appendToDisplay("Sorry..."); 
        } 
       } 
      } 
     }.start(); 
    } 

    public void appendToDisplay(String msg) { 
     display.append(msg + "\n"); 
    } 

    public static void main(String[] args) { 

    } 
} 
相關問題