Vincent
Vincent

Reputation: 23

Java chat server client issue

I followed this tutorial to make a chat with multiples client and one server: http://inetjava.sourceforge.net/lectures/part1_sockets/InetJava-1.9-Chat-Client-Server-Example.html but I have a problem, I want the client to send his username when he starts the app via the command prompt like this: java -jar Client.jar Jonny but I don't know how to do this. If someone can explain me.. Thanks for your answers.

Upvotes: 0

Views: 128

Answers (1)

gybandi
gybandi

Reputation: 1898

If you input your parameters like java -jar Client.jar Jonny, you can get the argument in the Client class' main method as a String array.

For example you can print out the first argument like this:

public static void main(String[] args)
{
  //This will output: "The first argument is: Jonny"
  System.out.println("The first argument is: "+args[0]);
}

All you have to do now is send this to the server. If you use the NakovChat example it could be something like this:

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();
        }

    }
}

Upvotes: 1

Related Questions