繁体   English   中英

Java聊天服务器客户端问题

[英]Java chat server client issue

我按照本教程与多客户端和一台服务器进行了聊天: http : //inetjava.sourceforge.net/lectures/part1_sockets/InetJava-1.9-Chat-Client-Server-Example.html,但是我有一个问题,我想要客户端在通过以下命令提示符启动应用程序时发送用户名: java -jar Client.jar Jonny但我不知道该怎么做。 如果有人可以解释我..谢谢您的回答。

如果输入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();
        }

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM