2016-03-04 96 views
0

我正在寫一個與Java服務器通信的程序。我試圖製作一個基本的通信程序,但我被重複的信息卡住了。一條消息有效,但是當我嘗試獲得多個而不關閉服務器和客戶端時,我失敗了。在我的使命中,我得到了一個我無法修復的錯誤。No line found掃描儀

我有以下類別:

客戶

import java.io.IOException; 
import java.io.PrintStream; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import java.util.Scanner; 

public class MainClass { 
    private static int port = 40021; 
    private static String ip = "localhost"; 

    public static void main(String[] args) throws UnknownHostException, 
      IOException { 
     String command, temp; 
     Scanner scanner = new Scanner(System.in); 
     Socket s = new Socket(ip, port); 
     Scanner scanneri = new Scanner(s.getInputStream()); 
     System.out.println("Enter any command"); 
     command = scanner.nextLine(); 
     PrintStream p = new PrintStream(s.getOutputStream()); 
     p.println(command); 
     temp = scanneri.nextLine(); 
     System.out.println(temp); 
    } 

} 

服務器

import java.io.IOException; 
import java.io.PrintStream; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.util.Scanner; 


public class MainClass { 
    public static void main(String args[]) throws IOException { 
     String command, temp; 
     ServerSocket s1 = new ServerSocket(40021); 
     Socket ss = s1.accept(); 
     Scanner sc = new Scanner(ss.getInputStream()); 
     while(true){ 
     command = sc.nextLine(); 
     temp = command + " Dat dus"; 
     PrintStream p = new PrintStream(ss.getOutputStream()); 
     p.println(temp); 
     } 

     } 


    } 

我在While循環得到一個錯誤。

Exception in thread "main" java.util.NoSuchElementException: No line found 

我能理解它爲什麼會給出錯誤,但我完全不知道如何讓它工作。

我希望有人能幫助我。提前致謝。

+1

在sc.nextLine()之前調用'if(sc.hasNextLine())'。首先會阻止,直到提交一些輸入。 –

+0

工作感謝! @SashaSalauyou –

回答

1

在您的服務器代碼這裏的線一直運行即使在客戶端已完成發送消息: -

while(true){ 
    command = sc.nextLine(); 
    temp = command + " Dat dus"; 
    PrintStream p = new PrintStream(ss.getOutputStream()); 
    p.println(temp); 
    } 

變化,爲: -

while(sc.hasNextLine()){ 
    command = sc.nextLine(); 
    temp = command + " Dat dus"; 
    PrintStream p = new PrintStream(ss.getOutputStream()); 
    p.println(temp); 
    } 

也可以增加你的整個服務器的代碼一個永久運行的while循環,因爲您不希望服務器在客戶端斷開連接後關閉,即: -

public static void main(String args[]) throws IOException 
{ 
    String command, temp; 
    ServerSocket s1 = new ServerSocket(40021); 
    while(true) 
    { 
     Socket ss = s1.accept(); 
     Scanner sc = new Scanner(ss.getInputStream()); 
     while(sc.hasNextLine()) 
     { 
     command = sc.nextLine(); 
     temp = command + " Dat dus"; 
     PrintStream p = new PrintStream(ss.getOutputStream()); 
     p.println(temp); 
     } 
    } 
} 
+0

非常感謝! –

+0

沒有probs @JesseVlietveld :) – 2016-03-04 18:19:10