编程实现,客户端输入两个数,服务端计算结果,并返回,要求服务端用多线程实现java代码
时间: 2023-08-04 13:35:21 浏览: 77
以下是一个用 Java 实现的多线程服务端,可以接收客户端输入的两个数,并计算结果返回给客户端:
```java
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class MultiThreadedServer {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
try (ServerSocket serverSocket = new ServerSocket(8888)) {
while (true) {
Socket socket = serverSocket.accept();
executorService.execute(new ServerTask(socket));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class ServerTask implements Runnable {
private final Socket socket;
public ServerTask(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
// 接收客户端输入的两个数
String[] nums = reader.readLine().split(" ");
int num1 = Integer.parseInt(nums[0]);
int num2 = Integer.parseInt(nums[1]);
// 计算结果
int result = num1 + num2;
// 返回结果给客户端
writer.write(Integer.toString(result));
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
客户端可以通过以下代码与服务端进行交互:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in))) {
// 输入两个数
System.out.print("请输入第一个数:");
String num1 = inputReader.readLine();
System.out.print("请输入第二个数:");
String num2 = inputReader.readLine();
// 发送两个数到服务端
writer.write(num1 + " " + num2);
writer.newLine();
writer.flush();
// 接收服务端返回的结果
String result = reader.readLine();
// 输出结果
System.out.println("计算结果为:" + result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意:上述代码没有对客户端输入的数进行校验,实际使用中应该添加相应的校验逻辑。
阅读全文