我试图将所有客户端连接到一台服务器。我做了一些研究,发现最简单的方法是为连接到服务器的每个客户端创建一个新线程。但是我已经停留在客户端断开连接并重新连接的部分。将多个客户端连接到一台服务器
客户
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我一直在编程大学几个月了,我不明白线程。所以我希望有人能为我解释。 –