java—实用小技巧——解析命令行参数
我们在进行项目中的调试的时候,特别是对于Server的调试,写出来的Client总是不方便改一些参数,要么就是修改到配置文件里,要么就是重新打包,不甚麻烦,这时候一个可以在命令行指定参数的功能就可以很好的解决了,
直接上代码:
public class Config {
@SuppressWarnings("unused")
private final static Logger LOGGER = Logger.getLogger(Config.class);
private static final Options OPTIONS = new Options();
private static final String OPTION_HELP = "h";
private static final String OPTION_SERVER_ADDRESS = "sa";
private static final String OPTION_SERVER_PORT = "sp";
private static final String OPTION_LOCAL_PORT = "lp";
private static final String OPTION_ENDPOINT = "ep";
private static final String OPTION_PAYLOAD = "d";
static String serverAddress;
static int serverPort;
static int localPort;
static String endpoint;
static String payload;
static {
OPTIONS.addOption(OptionBuilder.withDescription("Print Help").withLongOpt("help").create(OPTION_HELP));
OPTIONS.addOption(OptionBuilder.withDescription("server address").hasArg().withArgName("server_address")
.create(OPTION_SERVER_ADDRESS));
OPTIONS.addOption(OptionBuilder.withDescription("server port").hasArg().withArgName("server_port")
.create(OPTION_SERVER_PORT));
OPTIONS.addOption(OptionBuilder.withDescription("local port").hasArg().withArgName("local_port")
.create(OPTION_LOCAL_PORT));
OPTIONS.addOption(OptionBuilder.withDescription("endpoint name").hasArg().withArgName("endpoint")
.create(OPTION_ENDPOINT));
OPTIONS.addOption(
OptionBuilder.withDescription("payload in hex").hasArg().withArgName("payload").create(OPTION_PAYLOAD));
}
public static void printUsage(String message) {
if (message != null) {
System.out.println(message);
}
HelpFormatter formatter = new HelpFormatter();
String header = "\nEmulate Coap Client(s)";
String footer = "\n\nexample: java -cp coap-client.jar com.client.sim.SimClient -sa 23.212.7.182 -sp 5685 "
+ "-lp 11162 -ep 863783037777777 -d 00001111 \n";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(baos);
formatter.printHelp(writer, 200, "java -jar coap-client.jar ", header, OPTIONS, 4, 4, footer, true);
writer.close();
System.out.println(baos.toString());
}
/**
*
* @param parser
* @param args
* @return <code>true</code> if command line successfully parsed,
* <code>false</code> if a problem occurred or help param was
* specified
*/
static boolean parseArguments(CommandLineParser parser, String[] args) {
try {
CommandLine cmd;
cmd = parser.parse(OPTIONS, args);
if (cmd.hasOption(OPTION_HELP)) {
printUsage(null);
return false;
}
if (cmd.hasOption(OPTION_SERVER_ADDRESS)) {
serverAddress = cmd.getOptionValue(OPTION_SERVER_ADDRESS);
}
if (cmd.hasOption(OPTION_SERVER_PORT)) {
serverPort = Integer.parseInt(cmd.getOptionValue(OPTION_SERVER_PORT));
}
if (cmd.hasOption(OPTION_LOCAL_PORT)) {
localPort = Integer.parseInt(cmd.getOptionValue(OPTION_LOCAL_PORT));
}
if (cmd.hasOption(OPTION_ENDPOINT)) {
endpoint = cmd.getOptionValue(OPTION_ENDPOINT);
}
if (cmd.hasOption(OPTION_PAYLOAD)) {
payload = cmd.getOptionValue(OPTION_PAYLOAD);
}
} catch (Exception ex) {
printUsage(ex.getClass().getSimpleName() + ": " + ex.getMessage());
return false;
}
return true;
}
public static int getServerPort() {
return serverPort;
}
public static void setServerPort(int serverPort) {
Config.serverPort = serverPort;
}
public static int getLocalPort() {
return localPort;
}
public static void setLocalPort(int localPort) {
Config.localPort = localPort;
}
public static String getEndpoint() {
return endpoint;
}
public static void setEndpoint(String endpoint) {
Config.endpoint = endpoint;
}
public static String getPayload() {
return payload;
}
public static void setPayload(String payload) {
Config.payload = payload;
}
public static String getServerAddress() {
return serverAddress;
}
public static void setServerAddress(String serverAddress) {
Config.serverAddress = serverAddress;
}
}
调用:
private static DatagramSocket datagramSocket;
private static DatagramPacket datagramPacket;
public static void main(String[] args) {
CommandLineParser parser = new PosixParser();
if (!Config.parseArguments(parser, args)) {
return;
}
try {
/*** 发送数据 ***/
// 初始化datagramSocket,注意与前面Server端实现的差别
datagramSocket = new DatagramSocket(new InetSocketAddress(Config.getLocalPort()));
// 使用DatagramPacket(byte buf[], int length, InetAddress address, int port)函数组装发送UDP数据报
byte[] buf = Config.getPayload().getBytes();
InetAddress address = InetAddress.getByName(Config.getServerAddress());
datagramPacket = new DatagramPacket(buf, buf.length, address, Config.getServerPort());
// 发送数据
datagramSocket.send(datagramPacket);
/*** 接收数据 ***/
byte[] receBuf = new byte[1024];
DatagramPacket recePacket = new DatagramPacket(receBuf, receBuf.length);
datagramSocket.receive(recePacket);
String receStr = new String(recePacket.getData(), 0, recePacket.getLength());
System.out.println("Client Rece Ack: " + receStr + " -- "
+ Hex.encodeHexString(recePacket.getData()).substring(0, receStr.length() * 2));
System.out.println(recePacket.getPort());
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭socket
if (datagramSocket != null) {
datagramSocket.close();
}
}
}
命令行执行jar包:
java -cp coap-client-test-1.0-SNAPSHOT.jar com.client.sim.SimUdpClient -sa 127.0.0.1 -sp 10000 -lp 10006 -d ff
e8e91bf6b308130300011701590026006afe0000006037fc55ff026f6388010b01cd
这样就可以直接在命令行修改参数,愉快的测试啦!!!