im
port java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpEchoServer {
private DatagramSocket socket = null;
public UdpEchoServer(int port) throws SocketException {
socket = new DatagramSocket(port);
}
public void start() throws IOException {
System.out.println("启动了");
while(true){
//读取请求
DatagramPacket requestpacket = new DatagramPacket(new byte[4096],4096);
socket.receive(requestpacket);
String request = new String(requestpacket.getData(),0,requestpacket.getLength()).trim();
String response = process(request);
//返回响应
DatagramPacket responsepacket = new DatagramPacket(response.getBytes(),
response.getBytes().length,requestpacket.getSocketAddress());
socket.send(responsepacket);
System.out.printf("[%s;%d] req:%s ; res:%s\n",
requestpacket.getAddress().toString(),socket.getPort(),request,response);
}
}
public String process(String request){
return request;
}
public static void main(String[] args) throws IOException {
UdpEchoServer server = new UdpEchoServer(9090);
server.start();
}
}