写一个java程序:客户端和服务器建立套接字连接后,客户将如下格式的账单发送给服务器。 房租:2189元 水费:112.9元 电费:569元 物业费:832元 服务器返回给客户的信息是: 您的账单: 房租:2189元 水费:112.9元 电费:569元 物业费:832元 总计:3699元
时间: 2023-07-31 09:09:56 浏览: 137
好的,下面是Java代码实现:
服务端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
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(new OutputStreamWriter(socket.getOutputStream()), true);
String line = in.readLine();
String[] bills = line.split(" ");
double total = 0.0;
StringBuilder sb = new StringBuilder("您的账单:\n");
for (String bill : bills) {
String[] pair = bill.split(":");
double value = Double.parseDouble(pair[1]);
total += value;
sb.append(bill).append("元\n");
}
sb.append("总计: ").append(total).append("元");
out.println(sb.toString());
in.close();
out.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
String bill = "房租:2189元 水费:112.9元 电费:569元 物业费:832元";
out.println(bill);
String line = in.readLine();
System.out.println(line);
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意:本示例代码中,服务端只能处理一次客户端请求,如果要支持多次请求,需要使用多线程等技术。
阅读全文