java实现开发TCP客户端与服务端,客户端从键盘输入一个四则运算表达式(如“1+2”、“6/3”等)并发送给服务端。服务端接收后执行运行,并将结果返回给客户端
时间: 2024-06-13 21:09:16 浏览: 71
java实现客户端与服务端通信
5星 · 资源好评率100%
以下是Java实现开发TCP客户端与服务端,客户端从键盘输入一个四则运算表达式并发送给服务端,服务端接收后执行运行,并将结果返回给客户端的代码:
服务端代码:
```java
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started.");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client " + socket.getInetAddress() + " connected.");
new Thread(() -> {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
String expression;
while ((expression = reader.readLine()) != null) {
System.out.println("Received expression: " + expression);
// 计算表达式
int result = Calculator.calculate(expression);
// 发送结果
writer.println(result);
System.out.println("Sent result: " + result);
}
reader.close();
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
}
class Calculator {
public static int calculate(String expression) {
String[] tokens = expression.split(" ");
int a = Integer.parseInt(tokens[0]);
int b = Integer.parseInt(tokens[2]);
switch (tokens[1]) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
default:
throw new IllegalArgumentException("Invalid operator: " + tokens[1]);
}
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 8888);
System.out.println("Connected to server.");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String expression;
while ((expression = reader.readLine()) != null) {
// 发送表达式
out.println(expression);
// 接收结果
String result = in.readLine();
System.out.println("Result: " + result);
}
reader.close();
in.close();
out.close();
socket.close();
}
}
```
阅读全文