好吧,我的問題很簡單。我試圖做簡單的聊天,但我覺得從服務器斷開客戶端的檢測是強制性的。聊天工作正常(沒有這樣的檢測),當我使用簡單:套接字讀取()和就緒()互鎖,客戶端斷開連接檢測
if (this.in.ready()) //preinitialized buffered reader
this.dataIn=this.in.readLine();
我瀏覽過很多貼在這裏的網站/問題,我讀到ready()
應該因爲它阻止一切被中省略,這可能是真的,因爲當我刪除此ready()
我的聊天不再有效,但它使客戶端斷開連接的檢測。
爲了達到我的目標,我需要測試BufferedReader
是否通過readLine()
收到空值,但是這不起作用。
if (this.in.readLine()!=null){ //1. check if client disconnected
if (this.in.ready()) //2/
this.dataIn=this.in.readLine(); //3.
}
else
this.notice="Client disconnected!";
現在當我應用上面提供的代碼時會發生什麼。如果(1)阻塞內部ready()
(第2行)(如果需要讀取通過套接字(3)發送的實際消息),則返回初始值。
其他「訂單」不工作:
if (this.in.ready()){
this.dataIn=this.in.readLine();
}
else if (this.in.readLine()!=null)
this.notice="Client disconnected!";
這其中也不允許通過套接字發送消息。
*是,發送/ recieving因而可實現單獨的線程
* BufferedReader中被初始化一次
線程源代碼(如果ANY1需要它,以看看):
@Override
public void run() {
try {
if (this.isServer){
this.initServer();
this.initProcessData(sSocket);
}
else if (!this.isServer){
this.initClient();
this.initProcessData(clientSocket);
}
this.initDone=true;
} catch (IOException ex) {
Logger.getLogger(NetClass.class.getName()).log(Level.SEVERE, null, ex);
}
while(this.initDone){
try {
Thread.sleep(100);
if ((!this.dataOut.isEmpty())&&(this.dataOut!="")){
this.out.println(this.dataOut);
this.out.flush();
this.dataOut = "";
}
if (this.in.ready())
this.dataIn=this.in.readLine();
}
catch (IOException ex) {
Logger.getLogger(NetClass.class.getName()).log(Level.SEVERE, null, ex);
}
catch (InterruptedException ex) {
this.initDone=false;
Logger.getLogger(NetClass.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println(this.notice);
}
}
最糟糕的是,我有適當的客戶端斷開檢測或我有工作聊天。
任何人都可以讓我知道我應該怎麼做才能將這兩者結合在一起?任何幫助不勝感激。