简体   繁体   中英

How to access and/or read command line arguments from a separate file inside the run method of a thread (java socket programming)

I am trying to create program with three files (main function file, server file, client file)

I want to focus only on the main and server file for now.

The program will run as a server if the following command line arguments are present:

java DirectMessengerCombined -l 3000

If "-l" is not present, it will run as a client

In the server file there are two separate run methods for two separate threads (one for receiving messages, one for sending messages) (not sure how to resolve the fact that the method name "run" appears twice in the program)

The main function file is the one that contains the (String args[]) command line arguments

I am trying to access args[] in both of the the server thread run methods.

Code of main function file:

import java.io.IOException;
public class DirectMessengerCombined
{
    public static void main(String[] args) throws IOException
    {
        DirectMessengerClient Client1 = new DirectMessengerClient();
        DirectMessengerServer Server1 = new DirectMessengerServer();
        //DirectMessengerServer Server1 = new DirectMessengerServer(args[1], null, 0);
          for (int i = 0; i < args.length; i++)
          {
                if(!args[0].equals("-l"))
                {
                    Client1.ClientRun(args);
                }
                switch (args[0].charAt(0))
                {
                    case '-':
                    if(args[0].equals("-l"))
                    {   
                        Server1.ServerRun(args);
                    }

                }
           i=args.length + 20;
          } 
    }

}

As you can see, the "args" is passed inside the line of code that says:

 Server1.ServerRun(args);

In the following code, the method at the beginning named "ServerRun" has access to the real command line arguments (from the passed in parameter "String[] args"). I want to be able to use and/or access the "String args[]" from the ServerRun method parameters to be used inside the separate run methods to get the port number.

Code of Server:

import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class DirectMessengerServer
{
    private static Socket socket;
    boolean KeepRunning = true;

    void ServerRun(String[] args) 
    {
          //How do I get the String[] args in this method be able to access it in the run methods?

    }
    Thread ServerRecieve = new Thread();
    Thread ServerSend = new Thread ();
    //Run method of ServerSend
    public void run()
    {   
        System.out.println("Server sending thread is now running");
        try
        {         

            //Send the message to the server
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            //creating message to send from standard input
            String newmessage = "";
            try 
            {
                // input the message from standard input
                BufferedReader input= new BufferedReader( 
                new InputStreamReader(System.in));
                String line = "";

                line= input.readLine(); 
                    newmessage += line + " ";

            }
            catch ( Exception e )
            {
                System.out.println( e.getMessage() );
            }
            String sendMessage = newmessage;
            bw.write(sendMessage + "\n");
            bw.flush();
            System.out.println("Message sent to client: "+sendMessage);

            }

            catch (IOException e) 
            {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {

        }
  //  }
    }

//run method of ServerRecieve
public void run(String args[])
{   
    System.out.println("Server recieve thread is now running");
    try
    {
        System.out.println("Try block begins..");
        int port_number1= Integer.valueOf(args[1]);
        System.out.println("Port number is: " + port_number1);
        ServerSocket serverSocket = new ServerSocket(port_number1);
        //SocketAddress addr = new InetSocketAddress(address, port_number1);
        System.out.println( "Listening for connections on port: " + ( port_number1 ) );

        while(KeepRunning)
        {
            //Reading the message from the client

            socket = serverSocket.accept();    
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String MessageFromClient = br.readLine();
            System.out.println("Message received from client: "+ MessageFromClient);


        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {
        try {
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
}

My question is, how can I get the string[] args from inside the ServerRun parameters, store it somewhere to be used in the separate run methods later in the program?

In answer to the specific question of how to access the args in another method of the class, the following will work.

I would suggest moving the args parameter to the constructor rather than via method call, as shown here. Of course a method can set an instance variable, but then the instance variable cannot be final. As the variable should not need to change references, final is the most appropriate approach, I believe.

public class DirectMessengerServer
{
  private final String[] serverArgs; // <-- added variable
  private static Socket socket;
  boolean keeyRunning = true;

  public DirectMessengerServer(String[] args)
  {
      // set the instance variable
      this.serverArgs = args;
  }


  public void run()
  {
      // access the serverArgs instance variable
      System.out.println(serverArgs[0]);
  }


//
// from the dirver program    
//
public static void main(String[] args)
{
    // after verifying the args as desired
    DirectMessengerServer server1 = new DirectMessengerServer(args);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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