java 这是一个关于使用套接字连接编写网络程序的示例。客户输入三角形的三边并发送给服务器,服务器计算三角形的面积并返回给客户。
时间: 2024-03-27 15:35:06 浏览: 59
好的,以下是使用 Java 编写的简单客户端-服务器网络程序示例:
服务器端代码:
```java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Server {
public static void main(String[] args) {
try {
// 创建服务器套接字并监听客户端请求
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("Server is listening...");
while (true) {
// 接受客户端连接
Socket clientSocket = serverSocket.accept();
System.out.println("Connection from: " + clientSocket.getInetAddress());
try {
// 读取客户端发送的三角形三边
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String[] sides = in.readLine().split(" ");
double a = Double.parseDouble(sides[0]);
double b = Double.parseDouble(sides[1]);
double c = Double.parseDouble(sides[2]);
System.out.println("Received: " + a + " " + b + " " + c);
// 计算三角形面积并发送给客户端
double p = (a + b + c) / 2;
double area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(area);
System.out.println("Sent: " + area);
} catch (Exception e) {
e.printStackTrace();
}
// 关闭客户端连接
clientSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
// 创建客户端套接字并连接服务器
Socket clientSocket = new Socket("localhost", 8000);
while (true) {
// 输入三角形三边并发送给服务器
Scanner scanner = new Scanner(System.in);
System.out.print("Enter three sides of triangle: ");
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(a + " " + b + " " + c);
// 接受服务器返回的三角形面积并输出
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
double area = Double.parseDouble(in.readLine());
System.out.println("Area: " + area);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
当客户端运行时,它将要求用户输入三角形的三边,并将其发送到服务器。服务器接收这些数据,计算三角形面积并将其发送回客户端。客户端接收并显示面积。
阅读全文