我按照本教程与多个客户端和一个服务器聊天:http://inetjava.sourceforge.net/lectures/part1_sockets/InetJava-1.9-Chat-Client-Server-Example.html
但我有一个问题,我希望客户端在通过命令提示符启动应用程序时发送用户名,如下所示:
java -jar Client.jar Jonny
但我不知道该怎么做。
如果有人能解释我..
谢谢你的回答。
答案 0 :(得分:1)
如果输入java -jar Client.jar Jonny
之类的参数,则可以将Client类的main方法中的参数作为String数组获取。
例如,您可以打印出第一个参数:
public static void main(String[] args)
{
//This will output: "The first argument is: Jonny"
System.out.println("The first argument is: "+args[0]);
}
您现在要做的就是将其发送到服务器。如果您使用NakovChat示例,它可能是这样的:
public static void main(String[] args)
{
BufferedReader in = null;
PrintWriter out = null;
try {
// Connect to Nakov Chat Server
Socket socket = new Socket(SERVER_HOSTNAME, SERVER_PORT);
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(
new OutputStreamWriter(socket.getOutputStream()));
System.out.println("Connected to server " +
SERVER_HOSTNAME + ":" + SERVER_PORT);
//We print out the first argument on the socket's outputstream and then flush it
out.println(args[0]);
out.flush();
} catch (IOException ioe) {
System.err.println("Can not establish connection to " +
SERVER_HOSTNAME + ":" + SERVER_PORT);
ioe.printStackTrace();
System.exit(-1);
}
// Create and start Sender thread
Sender sender = new Sender(out);
sender.setDaemon(true);
sender.start();
try {
// Read messages from the server and print them
String message;
while ((message=in.readLine()) != null) {
System.out.println(message);
}
} catch (IOException ioe) {
System.err.println("Connection to server broken.");
ioe.printStackTrace();
}
}
}