java udp socket编程demo
时间: 2023-08-23 13:06:46 浏览: 134
以下是一个简单的Java UDP Socket编程示例,它包括一个服务器和一个客户端:
服务器端代码:
```java
import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String args[]) throws Exception {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("From Server:" + modifiedSentence);
clientSocket.close();
}
}
```
该示例中,服务器在端口号9876上监听客户端请求,并将收到的消息转换为大写字母形式返回给客户端。客户端从用户输入中读取一条消息,并将其发送到服务器。然后,客户端等待从服务器返回的响应,并在控制台上输出响应。
阅读全文