Java使用套接字连接编写一个网络程序,用户在客户端输入三角形的3条边长,客户端将他们发送给服务器端,服务器吧计算出的三角形的面积返回给客户端,客户端命令行窗口中显示面积值。
时间: 2023-06-26 19:06:00 浏览: 160
以下是一个简单的Java网络程序,实现了客户和服务器之间的通信,以计算三角形面积为例:
服务器端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.err.println("Could not listen on port: 8888.");
System.exit(1);
}
Socket clientSocket = null;
try {
System.out.println("Waiting for connection...");
clientSocket = serverSocket.accept();
System.out.println("Connection successful.");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received input: " + inputLine);
String[] sides = inputLine.split(",");
double a = Double.parseDouble(sides[0]);
double b = Double.parseDouble(sides[1]);
double c = Double.parseDouble(sides[2]);
// 计算三角形面积
double p = (a + b + c) / 2;
double area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
out.println(area);
System.out.println("Sent output: " + area);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java Client <host name>");
System.exit(1);
}
String hostName = args[0];
int portNumber = 8888;
try (
Socket socket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
String response = in.readLine();
System.out.println("Server response: " + response);
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
```
在客户端命令行窗口中输入三角形的3条边长,以逗号分隔,例如:
```
3,4,5
```
然后客户端将它们发送给服务器端。服务器端计算出三角形的面积,并将结果返回给客户端,客户端在命令行窗口中显示面积值。
阅读全文