客户端发送一串小写字符串给服务端,服务端接受后将字符串转为大写,然后发给客户端,写出这个过程的java的程序,包括客户端的程序和服务端的程序
时间: 2023-05-23 16:07:00 浏览: 149
以下是一个可能的Java程序,实现了客户端发送小写字符串给服务端,服务端将其转换为大写,然后发送回客户端的过程。这个程序使用TCP套接字通信,并且假设客户端和服务端在同一台计算机上运行。
客户端程序:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 8080);
Scanner scanner = new Scanner(System.in);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true)) {
System.out.println("Connected to server.");
while (true) {
System.out.print("Enter lowercase string (or 'exit' to quit): ");
String input = scanner.nextLine();
if (input.equals("exit")) {
break;
}
writer.println(input);
String output = reader.readLine();
System.out.println("Server response: " + output);
}
} catch (Exception e) {
System.err.println("Client error: " + e.getMessage());
}
}
}
```
服务端程序:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server started.");
while (true) {
try (Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true)) {
System.out.println("Client connected: " + socket.getInetAddress().getHostAddress());
String input = reader.readLine();
String output = input.toUpperCase();
writer.println(output);
}
}
} catch (Exception e) {
System.err.println("Server error: " + e.getMessage());
}
}
}
```
注意:这个程序仅仅是一个演示。在实际应用中,需要进行异常处理、输入验证、注册多个客户端等等。
阅读全文