UDP将请求发送到host:port并返回响应。
import java.io.IOException; import java.net.DatagramPacket;/*nowjava - 时 代 Java*/ import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketTimeoutException; public class Main{ public static void main(String[] argv) throws Exception{ String host = "nowjava.com"; int port = 2; String request = "nowjava.com"; System.out.println(getResponse(host,port,request)); } private static final String CLASS_NAME = UDPClientUtil.class .getSimpleName(); private static final int TIMEOUT = 10 * 1000; /** * Sends a request to the host:port and returns the response. * * @param host * @param port * @param request * @throws IOException */ public static String getResponse(String host, int port, String request) throws IOException { String method = CLASS_NAME + ".getResponse()";/**from 时 代 J a v a - N o w J a v a . c o m**/ DatagramSocket socket = new DatagramSocket(); socket.setSoTimeout(TIMEOUT); InetAddress addr = InetAddress.getByName(host); byte[] data = request.getBytes(); DatagramPacket packet = new DatagramPacket(data, 0, data.length, addr, port); LogUtil.log(method, "Sending request: " + request); socket.send(packet); LogUtil.log(method, "DONE Sending request: " + request); byte[] buf = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(buf, 0, buf.length, packet.getAddress(), packet.getPort()); LogUtil.log(method, "Waiting for response."); try { socket.receive(datagramPacket); } catch (SocketTimeoutException ex) { LogUtil.log(method, "Read timed out. No response received after " + TIMEOUT + "ms. Returning null."); return null; } String response = new String(datagramPacket.getData(), 0, datagramPacket.getLength()); LogUtil.log(method, "Got response: " + response); socket.close(); return response; } /** * Send article data gram packet to given host. * * @param host * @param port * @param article * @throws IOException */