我试图将所有客户端连接到一台服务器。我做了一些研究,发现最简单的方法是为连接到服务器的每个客户端创建一个新线程。但我已经陷入了客户端断开连接并重新连接的部分。
客户端
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);
}
}
}
}
当我连接一旦它正常工作但是一旦我断开客户端并尝试重新连接(或连接第二个客户端)它就不会出现错误或任何它不起作用。我试图尽可能保持基本。
我希望有人可以帮助我。提前谢谢。
答案 0 :(得分: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();
}
}