2013-03-24 82 views
1

我一直在尋找對谷歌小時,因爲我知道這是我現在面臨一個非常簡單的問題,但我無法找到一個簡單的解決我的問題。Java的TCP監聽環

我正在寫一個很基本的IRC客戶端,只需重新學習Java的繩索爲它是一個很長的時間,因爲我已經做任何編碼和我有一個項目,我想以後的事情。

雖然我堅持使用套接字監聽器,但如果需要,我可以提供代碼,但我真正需要的是如何創建一個監聽並已創建套接字的簡單教程,並儘快完成某些操作它收到任何數據。這個循環應該繼續下去,直到關閉套接字(從服務器的用戶斷開連接)

與我當前的代碼的問題是聽者似乎直到它接收到的數據掛起整個程序。我甚至在一個單獨的線程中放置了一個while循環,以便它可以掛起該線程直到數據到達,但它仍然掛起整個程序。

我不想被告知答案,我想知道如何找到答案。我甚至研究過創建一個事件驅動的監聽器,但是對於我所需要的,這似乎過於複雜。

我希望不要有張貼代碼,因爲它的一切我已經做了嘗試,並得到它的工作,但這裏的編輯後一片狼藉是我到目前爲止有:

ListenToServer.java:

class ListenToServer extends Thread{ 

JTextPane outputDestination = null; 
Socket establishedSocket = null; 

public void kickStartprep(Socket establishedSocket, JTextPane outputDestination){ 
    this.establishedSocket = establishedSocket; 
    this.outputDestination = outputDestination; 
} 


@Override 
public void run(){ 

    UpdateServerStatusWindow("Thread is running!", outputDestination); 


    BufferedReader inFromServer = null; 

    try{ 
    inFromServer = new BufferedReader(new InputStreamReader(establishedSocket.getInputStream())); 

     while (inFromServer.readLine().isEmpty() == false){ 
     UpdateServerStatusWindow(inFromServer.readLine(), outputDestination); 
     } 


    } 
    catch (Exception e){ 
     UpdateServerStatusWindow(e.toString(), outputDestination); 
    } 
} 


public void UpdateServerStatusWindow(String message, JTextPane destination){ 

    StyledDocument doc = destination.getStyledDocument(); 
    try 
{ 
doc.insertString(doc.getLength(), '\n' + message, null);  
} 
catch(Exception e){ 
    JOptionPane.showMessageDialog(null, "There was an error updating the server  message output window in the TCP Listner!"); 
    JOptionPane.showMessageDialog(null, e); 

} 

} 
} 

然後我從而調用:

MainGUI.java

ListenToServer serverListener = new ListenToServer(); 
    serverListener.kickStartprep(establishedConnection, ServerMessageOutput); 
    serverListener.run(); 
+3

你確定你使用的'Thread.start()''而不是Thread.run()'? – 2013-03-24 08:21:20

+3

向我們顯示您的代碼。 – 2013-03-24 08:21:31

+0

這是因爲讀取和對socket..Would寫有太大的幫助,如果你在這裏把你的代碼的線程塊.... – 2013-03-24 08:22:24

回答

2

甲朋友查看了這段代碼,發現問題出在我調用線程的方式。基本上,我需要打電話:

serverListener.start(); 

,而不是

serverListener.run(); 

這已經解決了這個問題,我的IRC客戶端現在連接到服務器正確。