gpt4 book ai didi

java - 将多个客户端连接到一台服务器

转载 作者:行者123 更新时间:2023-12-01 10:17:39 24 4
gpt4 key购买 nike

我正在尝试将所有客户端连接到一台服务器。我做了一些研究,发现最简单的方法是为连接到服务器的每个客户端创建一个新线程。但我已经陷入了客户端断开连接并重新连接的部分。

客户端

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

希望有人能帮助我。提前致谢。

最佳答案

您的服务器当前一次仅处理 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();
}
}

关于java - 将多个客户端连接到一台服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35805003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com