实验1 会结账的服务器。 客户端和服务器建立套接字连接后,客户将如下格式的账单发送给服务器。 房租:2189元 水费:112.9元 电费:569元 物业费:832元 服务器返回给客户的信息是: 您的账单: 房租:2189元 水费:112.9元 电费:569元 物业费:832元 总计:3699元 程序运行效果如图:输入服务器Ip127.0.0.1端口号4331java
时间: 2023-06-14 09:07:17 浏览: 237
很高兴为您解答这个问题。以下是Java实现的代码:
客户端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
String serverHostname = args[0];
int port = Integer.parseInt(args[1]);
Socket socket = new Socket(serverHostname, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String rent = "2189";
String water = "112.9";
String electricity = "569";
String property = "832";
out.println("rent:" + rent + ";water:" + water + ";electricity:" + electricity + ";property:" + property);
String response;
while ((response = in.readLine()) != null) {
System.out.println(response);
break;
}
out.close();
in.close();
socket.close();
}
}
```
服务器端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
int port = Integer.parseInt(args[0]);
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
String[] bills = inputLine.split(";");
int total = 0;
for (String bill : bills) {
String[] parts = bill.split(":");
int cost = Integer.parseInt(parts[1]);
total += cost;
}
out.println("您的账单:");
out.println(inputLine);
out.println("总计:" + total + "元");
break;
}
out.close();
in.close();
clientSocket.close();
}
}
}
```
运行时在控制台输入以下命令:
```
java Server 4331
```
然后打开另一个控制台,输入以下命令:
```
java Client 127.0.0.1 4331
```
运行后,您将看到客户端发送账单后,服务器返回的信息,如下所示:
```
您的账单:
rent:2189;water:112.9;electricity:569;property:832
总计:3702元
```
希望这可以帮助你!
阅读全文