简体   繁体   中英

Java readByte() blocks the application

the following loop seems to block the whole server application, if the client has suddenly disconnected and EOF exception is raised:

String a = "";
int amount = 1;
while(((cr = streamIn.readByte()) != EOF))
{
 if(amount < 100)
 {
  a+=(char)cr;
  amount++;
 }
 else
  break;
}

According to the function description: readByte(): receive a byte. the method will block, until data is available.

The question is, how can i make it timeout so it only blocks for a few seconds at most?

你有没有尝试过设置Socket.setSoTimeout()

What server is that ? I mean it blocks the thread that serves the client that suddenly drops...it should still serve the other clients

Look into using inputStream.available() which returns the number of bytes which can be retrieved without blocking.

(Untested) Example:

String a = "";
int amount = 1;
int available = 0;
while(true){
    int available = streamIn.available();
    if(available <= 0){
        continue;
    }   
    byte cr = streamIn.readByte();
    if(cr == EOF){
        break;
    }
    if(amount < 100){
        a+=(char)cr;
        amount++;
    }else{
        break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM