所以我为分配的前一部分创建了一个服务器和一个客户端,但现在我必须扩展/修改服务器,以便它可以同时处理多个客户端。 我知道我必须按照
的方式做点什么Server server1 = new Server();
Thread thread = new Thread(server1);
thread.start();
让Class Server实现Runnable。
但讲师关于多线程的注意事项并不是很清楚,而且我已经在这个问题的这一部分主演了很长时间但没有在哪里。
下面是我一次为一个客户端编写的代码,用于连接服务器。 任何帮助将不胜感激。
Server.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();
}
}
Client.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();
}
}
答案 0 :(得分:0)
你想要重复的是RMI几十年来一直在做的事情。 Java是开源的,因此您可以查看RMI如何工作并从中学习。您还可以在互联网上查看有/无RMI的多线程服务器的无数示例。