用java实现:实验1 会结账的服务器。 客户端和服务器建立套接字连接后,客户将如下格式的账单发送给服务器。 房租:2189元 水费:112.9元 电费:569元 物业费:832元 服务器返回给客户的信息是: 您的账单: 房租:2189元 水费:112.9元 电费:569元 物业费:832元 总计:3699元
时间: 2023-07-29 22:09:08 浏览: 172
以下是用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 = new ServerSocket(8888);
System.out.println("服务器启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端连接成功!");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String line;
double total = 0.0;
while ((line = in.readLine()) != null) {
if (line.equals("done")) {
break;
}
String[] items = line.split(":");
if (items.length == 2) {
String type = items[0].trim();
double amount = Double.parseDouble(items[1].trim());
total += amount;
out.println(type + ": " + amount + "元");
}
}
out.println("总计: " + total + "元");
socket.close();
serverSocket.close();
}
}
```
客户端代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("房租:2189元");
out.println("水费:112.9元");
out.println("电费:569元");
out.println("物业费:832元");
out.println("done");
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
socket.close();
}
}
```
运行该程序,先运行服务器端代码,然后再运行客户端代码,就可以实现会结账的服务器了。
阅读全文