利用ServerSocket类和Socket类,编写服务器端和客户端程序,实现客户端发送整数作为圆的半径(整数从键盘输入)给服务器端,服务器端根据圆半径计算出其面积,并把面积返回给客户端。(本地主机做服务器) 分别把服务器端和客户端的代码截图提交在答案处。
时间: 2024-02-26 14:57:48 浏览: 94
很抱歉,作为语言模型的我无法进行截图操作,但是我可以为您提供相应的Java代码实现:
服务器端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(8888);
System.out.println("Server started...");
while (true) {
Socket socket = server.accept();
System.out.println("Client connected...");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int radius = Integer.parseInt(reader.readLine());
double area = Math.PI * radius * radius;
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(area);
writer.flush();
socket.close();
}
} catch (Exception 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(System.in));
System.out.print("Enter radius: ");
int radius = Integer.parseInt(reader.readLine());
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(radius);
writer.flush();
BufferedReader serverReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
double area = Double.parseDouble(serverReader.readLine());
System.out.println("Area: " + area);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在运行客户端程序时,需要先运行服务器端程序,然后输入半径,即可得到计算后的圆面积。
阅读全文