简体   繁体   English

如何从线程的run方法内部的单独文件访问和/或读取命令行参数(Java套接字编程)

[英]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 如果“ -l”不存在,它将作为客户端运行

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 主要功能文件是包含(String args [])命令行参数的文件

I am trying to access args[] in both of the the server thread run methods. 我正在尝试在两个服务器线程运行方法中访问args []。

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: 如您所见,“ args”在代码行中传递,该行显示:

 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"). 在下面的代码中,开头为“ ServerRun”的方法可以访问实际的命令行参数(来自传入的参数“ 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. 我希望能够使用和/或访问ServerRun方法参数中的“ String args []”,以在单独的运行方法中使用以获得端口号。

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? 我的问题是,如何从ServerRun参数内部获取string [] args,并将其存储在程序稍后的单独运行方法中使用的某个位置?

In answer to the specific question of how to access the args in another method of the class, the following will work. 为了回答有关如何在该类的另一种方法中访问args特定问题,将执行以下操作。

I would suggest moving the args parameter to the constructor rather than via method call, as shown here. 我建议将args参数移至构造函数,而不要通过方法调用,如此处所示。 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. 我认为,由于变量不需要更改引用,因此final是最合适的方法。

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

}

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

相关问题 如何从命令行使用 arguments 运行 Java 方法? - How to run Java method with arguments from command line? Java从主方法调用命令行参数到一个单独的方法 - Java invoking command line arguments from the main method to a separate method Maven:如何从传递 arguments 的命令行运行 a.java 文件 - Maven: How to run a .java file from command line passing arguments Java从命令行参数读取并打印文件 - Java read a file and print it, from command line arguments 如何从命令行在Java中读取文件? - How to read file from command line in java? 如何从命令行通过vm参数运行Java项目? - How to run a java project with vm arguments from command line? 如何使用来自java程序的参数运行bat文件? (尝试使用命令行工具自动化) - How to run bat file with arguments from a java program? (Trying to automate using a Command Line Tool ) 如何使用文件中的不同命令行参数运行相同的Java程序 - How to run the same java program with different command line arguments from a file 无法读取Java命令行参数 - Java Command line arguments not read java-如何在Windows命令行中运行JAR文件,该命令行的运行时参数包含“&lt;”和“&gt;”字符 - java- how to run JAR file in Windows command line which has run time arguments containing “<” and “>” chars
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM