【发布时间】:2015-06-01 18:34:33
【问题描述】:
所以我已经为之前的作业部分创建了一个服务器和一个客户端,但现在我必须扩展/修改服务器,以便它可以同时处理多个客户端。 我知道我必须按照
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();
}
}
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();
}
}
【问题讨论】:
-
阅读教程(例如docs.oracle.com/javase/tutorial/essential/concurrency),然后尝试一下。您的讲师笔记并不是唯一可以免费获得有关多线程信息的地方。整个网络都在您的掌控之中。
-
你试过
executorservice,semaphore吗?? -
一般来说,您需要一个线程来侦听新连接,从而在连接到达时产生新线程或任务。
标签: java multithreading concurrency runnable concurrent-programming