[英]reading multiple lines from inputstream socket Java
我想從inputstream套接字讀取多行。
public void sendAsync(HashSet<Socket> socketHashset, Vector<String> vectors,
PrintWriter printwriter) throws IOException, InterruptedException {
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(() -> {
for(Socket v : socketHashset){
//this.printwriter = new PrintWriter(v.getOutputStream(),true);
for(String str: vectors ){
this.printwriter.println(str);
this.printwriter.flush();
}
}
});
/* Receiver */
while(true){
try {
printWriter.println(keybordScanner.nextLine())
while(scannerBuffer.hasNextLine()){
System.out.println(scannerBuffer.nextLine());
}
} catch(NoSuchElementException e){
e.printStackTrace();
}
}
}
問題是編譯器正在阻止,然后正在檢查“ hasNextLine”
while(scannerBuffer).hasNextLine())
我該如何解決這個問題? 一些替代方案。
如果沒有下一行,scannerBuffer.hasNextLine()不會返回false,但是將等待一行,在這種情況下,它將返回true,或者在套接字關閉時,將返回一個異常。 如果您希望程序在等待輸入時能夠執行其他操作,請創建一個線程以讀取輸入。 在等待輸入時,線程將被阻塞,但是程序的其余部分則不會。
Thread readingThread=new Thread(new readFromSock(scannerBuffer));
readingThread.start();
然后再上一堂課:
class readFromSock implements Runnable{
Scanner scannerBuffer;
public readFrom(Scanner scan){
scannerBuffer=scan;
}
public void run(){
try {
while(scannerBuffer.hasNextLine()){
System.out.println(scannerBuffer.nextLine());
}
} catch(NoSuchElementException e){
e.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.