我試圖將所有客戶端連接到一臺服務器。我做了一些研究,發現最簡單的方法是爲連接到服務器的每個客戶端創建一個新線程。但是我已經停留在客戶端斷開連接並重新連接的部分。將多個客戶端連接到一臺服務器
客戶
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);
}
}
}
}
當我連接,一旦它工作正常,但只要我斷開客戶端,並嘗試重新連接(或連接第二個客戶端),它並沒有給一個錯誤或任何它只是不起作用。我試圖儘可能保持基本。
我希望有人能夠幫助我。提前致謝。
所以,根據你的研究,你應該已經創建了每一個新的線程客戶端連接在服務器上。你正在做的那個部分在哪裏? – RealSkeptic
@RealSkeptic我一直在編程大學幾個月了,我不明白線程。所以我希望有人能爲我解釋。 –