使用java写一个本地ip为服务器地址的udp服务器
时间: 2024-03-21 22:38:59 浏览: 56
以下是使用Java编写一个本地IP为服务器地址的UDP服务器的示例代码:
```java
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws Exception {
// 创建UDP数据报套接字并绑定到本地IP
DatagramSocket serverSocket = new DatagramSocket(null);
InetSocketAddress address = new InetSocketAddress("localhost", 1234);
serverSocket.bind(address);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
// 接收UDP数据报
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received message: " + message);
// 发送UDP数据报
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
String responseMessage = "Hello from server";
sendData = responseMessage.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
}
}
}
```
在上面的代码中,我们首先创建了一个UDP数据报套接字,并将其绑定到本地IP地址“localhost”和端口号“1234”。然后我们进入一个无限循环,在每次循环中接收客户端发送的UDP数据报,并将其解析为字符串。然后,我们从数据报中获取客户端的IP地址和端口号,并使用这些信息创建一个新的UDP数据报,将其发送回客户端。
请注意,此示例仅用于演示目的,实际应用程序需要添加错误处理代码以及在程序退出时正确关闭套接字等清理操作。
阅读全文