JAVA代码实现编写一个客户/服务器程序,服务器的功能是计算圆的面积。客户端将圆的半径发送给服务器端,服务器端计算得出的圆面积发送给客户端,并在客户端显示。 1、 多线程 2、 字节流—不同的流。Buffered----Data 3、 Send(),Receive()
时间: 2024-11-05 18:32:24 浏览: 19
在Java中,我们可以创建一个简单的客户机/服务器架构来计算圆的面积。这里我们使用Socket编程,涉及到多线程、字节流以及缓冲区处理。以下是基本步骤:
**1. 多线程**
首先,服务器需要一个单独的线程来接收请求并计算圆的面积。服务器端代码可能如下:
```java
import java.io.*;
import java.net.*;
public class Server {
private static final int PORT = 9000;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server started on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
Thread clientThread = new ClientHandler(clientSocket);
clientThread.start();
}
}
private static class ClientHandler extends Thread {
private Socket socket;
private DataInputStream in;
private DataOutputStream out;
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
// 接收半径,计算面积并返回
double radius = readDoubleFromStream(in);
double area = calculateCircleArea(radius);
writeDoubleToStream(out, area);
// 关闭连接
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 如果异常结束,关闭资源
try {
if (out != null) out.close();
if (in != null) in.close();
} catch (IOException ignored) {}
}
}
// ...其他方法,如读取和写入双精度数
}
}
```
**2. 字节流 - 数据类型转换**
`readDoubleFromStream` 和 `writeDoubleToStream` 这样的方法用于在流之间传输双精度数值,通常会涉及类型转换:
```java
private static double readDoubleFromStream(DataInputStream stream) throws IOException {
byte[] buffer = new byte[8]; // Double is 8 bytes long
stream.readFully(buffer);
return ByteBuffer.wrap(buffer).asDoubleBuffer().get(0);
}
private static void writeDoubleToStream(DataOutputStream stream, double value) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putDouble(value);
stream.write(buffer.array());
}
```
**3. 发送和接收数据**
`accept()` 和 `send()`/`receive()` 在这里是通过Socket API完成的。`accept()` 等待新客户端连接,而 `socket.getOutputStream()` 和 `socket.getInputStream()` 分别用于向客户端发送数据和从客户端接收数据。
```java
// 客户端示例
public class Client {
public static void main(String[] args) throws IOException {
String host = "localhost";
int port = 9000;
Socket socket = new Socket(host, port);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
// 发送半径
double radius = 5.0;
writeDoubleToStream(outputStream, radius);
// 接收并显示面积
double receivedArea = readDoubleFromStream(inputStream);
System.out.println("Received area: " + receivedArea);
// 关闭流和连接
inputStream.close();
outputStream.close();
socket.close();
}
}
```
阅读全文