使用Java写一个使用套接字连接编写一个网络程序,用户在客户端输入三角形的3条边长,客户端将他们发送给服务器端,服务器吧计算出的三角形的面积返回给客户端,客户端命令行窗口中显示面积值程序
时间: 2023-12-03 15:46:57 浏览: 115
以下是使用Java编写的网络程序,实现了客户端输入三角形的3条边长,服务器计算出三角形的面积并返回给客户端,客户端命令行窗口中显示面积值的功能。
Server.java
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
// 创建一个ServerSocket在端口8888监听客户请求
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.err.println("Could not listen on port: 8888.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println("等待连接...");
try {
// 使用accept()阻塞等待客户请求,有客户请求到来则产生一个Socket对象,并继续执行
clientSocket = serverSocket.accept();
System.out.println("连接成功!");
// 由Socket对象得到输入流,并构造相应的BufferedReader对象
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// 由Socket对象得到输出流,并构造PrintWriter对象
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
double a, b, c, s, area;
while ((inputLine = in.readLine()) != null) {
// 从客户端读取三角形的3条边长
a = Double.parseDouble(inputLine);
b = Double.parseDouble(in.readLine());
c = Double.parseDouble(in.readLine());
// 计算三角形的面积
s = (a + b + c) / 2;
area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
// 将面积返回给客户端
out.println(area);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
}
}
```
Client.java
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// 创建一个Socket对象,指定需要连接的服务器的地址和端口号
socket = new Socket("localhost", 8888);
// 由Socket对象得到输出流,并构造相应的PrintWriter对象
out = new PrintWriter(socket.getOutputStream(), true);
// 由Socket对象得到输入流,并构造相应的BufferedReader对象
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
// 从命令行读取三角形的3条边长,并发送给服务器
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
out.println(stdIn.readLine());
out.println(stdIn.readLine());
// 从服务器读取计算出的三角形面积,并在命令行窗口中显示
System.out.println("面积为: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
socket.close();
}
}
```
阅读全文