gpt4 book ai didi

java - 修改服务器以允许多个客户端同时连接

转载 作者:行者123 更新时间:2023-12-03 13:12:10 28 4
gpt4 key购买 nike

因此,我为分配的前一部分创建了一个服务器和一个客户端,但是现在我必须扩展/修改服务器,以便它可以同时处理多个客户端。
我知道我必须遵循以下原则

Server server1 = new Server();

Thread thread = new Thread(server1);

thread.start();

并让Class Server实现Runnable。

但是,讲师们对多线程的说明还不是很清楚,我很长时间以来一直在这部分问题上担任主角,却一无所获。

下面是我一次为一个客户端编写的用于连接服务器的代码。
任何帮助将非常感激。

服务器.java
public class Server {

ArrayList<String> tokens = new ArrayList<String>();

private Socket s;
private Scanner in;
private PrintWriter out;

public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(1234);
Server serverInstance = new Server();
System.out.println("Server running. Waiting for a client to connect...");
while (true) {
serverInstance.s = server.accept();
System.out.println("Client connected");
serverInstance.run();
System.out.println("Client disconnected. Waiting for a new client to connect...");
}
}

public void start() {
System.out.println("Starting " + threadName);
if (t == null) {
t = new Thread(this, threadName);
t.start();
}
}

public void run() {
try {
try {
in = new Scanner(s.getInputStream());
out = new PrintWriter(s.getOutputStream());
doService(); // the actual service
}
finally {
s.close();
}
}
catch (IOException e) {
System.err.println(e);
}
}

public void doService() throws IOException {
while (true) {
if (!in.hasNext())
return;
String request = in.next();
System.out.println("Request received: " + request);
// (...) test for type of request here (not implemented)
Request(request);
}
}

public void Request(String request) {

String amountStr = in.next();
if (request.startsWith("SUBMIT")) {
if (tokens.size() < 10) {
tokens.add(amountStr);
System.out.println("Token added");
out.println("OK");
}
else {
System.err.println("Error");
out.println("Error");
}
}
else if (request.startsWith("REMOVE")) {
if (tokens.contains(amountStr)) {
tokens.remove(amountStr);
System.out.println("Tokens removed");
out.println("OK");
}
else {
System.err.println("Error");
out.println("Error");
}

}
else if (request.equals("QUIT")) {
System.err.println("Program ended");
out.println("Program ended");
}

tokens.sort(null);
System.out.println(tokens);
out.flush();
}
}

客户端.java
public class Client {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 1234);
InputStream instream = s.getInputStream();
OutputStream outstream = s.getOutputStream();
Scanner in = new Scanner(instream);
PrintWriter out = new PrintWriter(outstream);
String request = "SUBMIT hello \n";
out.print(request);
out.flush();
String response = in.nextLine();
System.out.println("Token: " + response);
s.close();
}
}

最佳答案

您要复制的是RMI数十年来一直在做的事情。 Java是开源的,因此您可以查看RMI的工作原理并从中学习。您也可以在Internet上查找带有/不带有RMI的无数多线程服务器的示例。

关于java - 修改服务器以允许多个客户端同时连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29317503/

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