*/
public final DatagramPacket send(final String host, final int port,
final byte[] bytes) throws IOException {
DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress
.getByName(host), port);
ds.send(dp);
return dp;
}
/**
* 接收从指定的服务端发回的数据.
* @param lhost 服务端主机
* @param lport 服务端端口
* @return 返回从指定的服务端发回的数据.
* @throws Exception
*/
public final String receive(final String lhost, final int lport)
throws Exception {
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String info = new String(dp.getData(), 0, dp.getLength());
return info;
}
* 关闭udp连接.
*/
public final void close() {
try {
ds.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 测试客户端发包和接收回应信息的方法.
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
UdpClientSocket client = new UdpClientSocket();
String serverHost = "127.0.0.1";
int serverPort = 3344;
client.send(serverHost, serverPort, ("你好,阿蜜果!").getBytes());
String info = client.receive(serverHost, serverPort);
System.out.println("服务端回应数据:" + info);
}
}