利用java语言提供的socket技术,建立一个c/s模式的应用,允许客户端用户输入2个整数,服务器端接收这2个整数,并计算出它们的和、差、积、商,最后送回客户端。
时间: 2023-04-28 08:01:21 浏览: 375
这个应用可以通过以下步骤实现:
1. 客户端连接服务器端的socket,发送2个整数给服务器端。
2. 服务器端接收这2个整数,并进行计算。
3. 服务器端将计算结果发送回客户端。
4. 客户端接收服务器端发送的计算结果。
具体实现可以参考以下代码:
服务器端:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端已连接:" + socket.getInetAddress().getHostAddress());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int num1 = Integer.parseInt(reader.readLine());
int num2 = Integer.parseInt(reader.readLine());
int sum = num1 + num2;
int diff = num1 - num2;
int product = num1 * num2;
int quotient = num1 / num2;
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
writer.println("和:" + sum);
writer.println("差:" + diff);
writer.println("积:" + product);
writer.println("商:" + quotient);
socket.close();
}
}
}
```
客户端:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
System.out.print("请输入第一个整数:");
int num1 = Integer.parseInt(reader.readLine());
writer.println(num1);
System.out.print("请输入第二个整数:");
int num2 = Integer.parseInt(reader.readLine());
writer.println(num2);
BufferedReader serverReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("计算结果:");
System.out.println(serverReader.readLine());
System.out.println(serverReader.readLine());
System.out.println(serverReader.readLine());
System.out.println(serverReader.readLine());
socket.close();
}
}
```
阅读全文