2016-03-04 123 views
0

我試圖將所有客戶端連接到一臺服務器。我做了一些研究,發現最簡單的方法是爲連接到服務器的每個客戶端創建一個新線程。但是我已經停留在客戶端斷開連接並重新連接的部分。將多個客戶端連接到一臺服務器

客戶

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

public class Test { 
    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); 
     while (true) { 
      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); 
     while (true) { 
      Socket ss = s1.accept(); 
      Scanner sc = new Scanner(ss.getInputStream()); 
      while (sc.hasNextLine()) { 
       command = sc.nextLine(); 
       temp = command + " this is what you said."; 
       PrintStream p = new PrintStream(ss.getOutputStream()); 
       p.println(temp); 
      } 
     } 
    } 
} 

當我連接,一旦它工作正常,但只要我斷開客戶端,並嘗試重新連接(或連接第二個客戶端),它並沒有給一個錯誤或任何它只是不起作用。我試圖儘可能保持基本。

與一個客戶機的輸出: Correct output

當我嘗試連接第二個客戶端: Output with 2 clients connected

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

+0

所以,根據你的研究,你應該已經創建了每一個新的線程客戶端連接在服務器上。你正在做的那個部分在哪裏? – RealSkeptic

+0

@RealSkeptic我一直在編程大學幾個月了,我不明白線程。所以我希望有人能爲我解釋。 –

回答

1

您的服務器目前在一個時間只能處理1的客戶端,使用線程爲每個客戶端,請修改服務器代碼: -

public static void main(String[] args) throws IOException 
{ 
    ServerSocket s1 = new ServerSocket(40021); 
    while (true) 
    { 
     ss = s1.accept(); 
     Thread t = new Thread() 
     { 
      public void run() 
      { 
       try 
       { 
        String command, temp; 
        Scanner sc = new Scanner(ss.getInputStream()); 
        while (sc.hasNextLine()) 
        { 
         command = sc.nextLine(); 
         temp = command + " this is what you said."; 
         PrintStream p = new PrintStream(ss.getOutputStream()); 
         p.println(temp); 
        } 
       } catch (IOException e) 
       { 
        e.printStackTrace(); 
       } 
      } 
     }; 
     t.start(); 
    } 
} 
+0

是的,但這並不能解決問題。它沒有例外。 –

+0

@JesseVlietveld,當你的主函數拋出IOException異常時,當客戶端斷開連接,因爲異常被拋出關閉服務器的主函數時,程序退出,你可以刪除它並單獨放置一個try catch,或者可以不必要地將它保留在那裏並把它放在 – 2016-03-04 20:16:09

+0

我不認爲你理解我。問題是它沒有給出錯誤或例外。它只是沒有顯示任何東西。我會更詳細地更新我的文章。 –

相關問題