Java中利用UDP实现,客户端给服务端发送小写字母文本,服务端会将文本转成大写在返回给客户端
时间: 2024-12-23 20:22:35 浏览: 3
在Java中,可以使用DatagramSocket和DatagramPacket类配合UDP(User Datagram Protocol,用户数据报协议)来实现在客户端和服务端之间的简单文本通信,其中服务端将接收到的小写字母转换为大写后再返回。
以下是简单的步骤:
**客户端(Client.java)**:
```java
import java.io.*;
import java.net.*;
public class Client {
private static final String SERVER_ADDRESS = "localhost";
private static final int PORT = 9090;
public static void main(String[] args) throws IOException {
DatagramSocket clientSocket = new DatagramSocket();
try {
String message = "hello world"; // 小写字母文本
byte[] sendData = message.getBytes("UTF-8");
InetAddress serverAddress = InetAddress.getByName(SERVER_ADDRESS);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, PORT);
clientSocket.send(sendPacket);
// 接收服务端响应
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String response = new String(receivePacket.getData(), "UTF-8").toUpperCase(); // 转换为大写并打印
System.out.println("Response from server: " + response);
} finally {
clientSocket.close();
}
}
}
```
**服务端(Server.java)**:
```java
import java.io.*;
import java.net.*;
public class Server extends Thread {
private static final int PORT = 9090;
private DatagramSocket serverSocket = null;
@Override
public void run() {
try {
serverSocket = new DatagramSocket(PORT);
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// 接收客户端消息并转换为大写
serverSocket.receive(packet);
String message = new String(packet.getData(), "UTF-8").toUpperCase();
// 构造回复
byte[] reply = message.getBytes("UTF-8");
InetAddress clientAddress = packet.getAddress();
int clientPort = packet.getPort();
DatagramPacket replyPacket = new DatagramPacket(reply, reply.length, clientAddress, clientPort);
serverSocket.send(replyPacket);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new Server().start();
}
}
```
当客户端运行并发送字符串"hello world"时,服务端会将其转换为"HELLO WORLD"并返回给客户端。
阅读全文