向控制台应用程序发送命令

向控制台应用程序发送命令

本文介绍了向控制台应用程序发送命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证一些东西,因为在我的头是有意义的,但在Java,它不工作。



我试图运行另一个Jar文件通过我的申请。一个Minecraft服务器,准确。我有所有的基础(使用 ProcessBuilder ,执行参数,等待退出代码等),但有一件事,我不能弄清楚。向应用程序发送命令。这里是 CommandLineSender 类的一部分:

  public class CommandLineSender extends Thread { 

private BufferedWriter输出;
private InputStream source; //在创建对象时设置为System.in
private boolean stopRequested;

public CommandLineSender(Process sendTo,InputStream source){
this.output = new BufferedWriter(new OutputStreamWriter(sendTo.getOutputStream()));
this.source = source;
System.out.println(Source InputStream initiated:+ source.toString());
this.stopRequested = false;
}

@Override
public void run(){
System.out.println(Run called。
Scanner cmdScanner = new Scanner(source);
while(cmdScanner.hasNextLine()&&!stopRequested){
System.out.println(Has next line);
String msg = cmdScanner.nextLine();
write(msg);
System.out.println(Wrote:+ msg);
}

//关闭扫描器和BufferedWriter

System.out.println(Closed。

}

//其他各种方法

protected void write(String msg){
try {
输出。写(msg);
} catch(IOException e){
System.err.println(由于未处理的IOException而无法写入消息:+ e.getMessage());
}

}

我得到的输出是:

 (默认Minecraft服务器输出)

help //我的命令
有下一行
Wrote:help



这可能没关系,但我使用这些参数执行我的服务器:

  java -Xmx1024M -Xms1024M -jar(到服务器jar的路径)nogui 



感谢您的时间。

解决方案

是一个通过其过程操作C程序的Java程序的一个例子(你也可以操作一个Java程序)。我写了这几年前。有C或Java的接收器程序和Java的发送器。查看:



C Receiver

  #include< stdio.h> 
#include< stdlib.h>
#include< stdbool.h>
#include< string.h>

int main(){

char message [50] = {0};

while(true){

gets(message);
printf(string \%s\received ... \\\
,message);

//强制流刷新
fflush(stdout);
fflush(stderr); // java程序不会在错误流中写入,所以这一行(对于这个例子)是不相关的

//如果java程序发送一个end命令(这里的消息) while
if(!strcmp(end,message)){
break;
}

}

return 0;

}

Java Receiver(等于C程序)

  import java.util。*; 

public class MessageReceiver {

public static void main(String [] args){

扫描程序扫描= new Scanner(System.in);

while(true){

String message = scan.nextLine();
System.out.printf(string \%s\received ... \\\
,message);

System.out.flush();
System.errorflush();

if(message.equals(end)){
break;
}

}

}

}

Java Sender

  import java.io. * ; 
import java.util。*;

public class Sender {

/ **
* @param参数命令行参数
* /
public static void main String [] args){
new Sender()。execute();
}

public void execute(){

try {

//执行命令(C可执行文件)
进程process = Runtime.getRuntime()。exec(MessageReceiver.exe);

//或,执行MessageReceiver类
//进程process = Runtime.getRuntime()。exec(java MessageReceiver);

//创建流gobblers,一个用于输入流,一个用于
//错误流。这些破坏者将消耗这些流。
StreamGobbler sgInput = new StreamGobbler(
process.getInputStream(),input);
StreamGobbler sgError = new StreamGobbler(
process.getErrorStream(),error);

//为每个流gobbler创建一个线程并启动它们
new Thread(sgInput).start();
new Thread(sgError).start();

//使用过程输出流创建PrintWriter
PrintWriter writer = new PrintWriter(process.getOutputStream());

//准备读取用户输入
扫描仪扫描=新扫描仪(System.in);

while(true){

System.out.println(发送命令:);
String command = scan.nextLine();

//发送命令到进程
//模拟用户输入(注意\\\

writer.write(command);
writer.write(\\\
);
writer.flush();

//如果命令结束,结束这个应用程序
if(command.equals(end)){
break;
}

}

} catch(IOException ioe){
ioe.printStackTrace();
}

}

/ **
*用于使用进程流的线程。
*基于此处提供的实现:
* http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1
*
* @author David Buzatto
* /
私人类StreamGobbler实现Runnable {

private InputStream is;
private String类型;
private FileWriter fw;

public StreamGobbler(InputStream is,String type){
this.is = is;
this.type = type;
}

public StreamGobbler(InputStream is,String type,File file)
throws IOException {
this.is = is;
this.type = type;
this.fw = new FileWriter(file);
}

@Override
public void run(){
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while((line = br.readLine())!= null){
if(fw!= null){
fw.write(line +\\\
);
} else {
System.out.println(type +>+ line);
}
}
if(fw!= null){
fw.close();
}
} catch(IOException ioe){
ioe.printStackTrace();
}
}
}

}

要运行代码,请编译C程序或MessageReceiver类。将可执行文件放在Sender类的同一文件夹中,进行编译并运行。 end命令将完成接收者和发送者。



还要看看这篇文章: p>

I want to verify something, because in my head it makes sense, but in Java, it doesn't work.

I am trying to run another Jar file through my application. A Minecraft server, to be precise. I have all the basics down (using ProcessBuilder, executing with arguments, waiting for an exit code, etc.), but there is one thing that I cannot figure out. Sending commands to the application. Here part of my CommandLineSender class:

public class CommandLineSender extends Thread {

    private BufferedWriter output;
    private InputStream source;  // Set to System.in when creating the object
    private boolean stopRequested;

    public CommandLineSender(Process sendTo, InputStream source) {
        this.output = new BufferedWriter(new OutputStreamWriter(sendTo.getOutputStream()));
        this.source = source;
        System.out.println("Source InputStream initiated: " + source.toString());
        this.stopRequested = false;
    }

    @Override
    public void run() {
        System.out.println("Run called.");
        Scanner cmdScanner = new Scanner(source);
        while (cmdScanner.hasNextLine() && !stopRequested) {
            System.out.println("Has next line");
            String msg = cmdScanner.nextLine();
            write(msg);
            System.out.println("Wrote: " + msg);
        }

        // Close the scanner and BufferedWriter

        System.out.println("Closed.");

    }

    // Other various methods

    protected void write(String msg) {
        try {
            output.write(msg);
        } catch (IOException e) {
            System.err.println("Unable to write message because of an unhandled IOException: " + e.getMessage());
        }

    }

The output I get is this:

(Default Minecraft server output)

help  // My command
Has next line
Wrote: help

This may not matter, but I am executing my server with these arguments:

java -Xmx1024M -Xms1024M -jar (path to server jar) nogui

Thank you for your time.

解决方案

Here is an example of a Java program that manipulates a C program through its process (you can manipulate a Java program too). I wrote this some years ago. There is the receiver program in C or Java and the sender in Java. Take a look:

C Receiver

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

int main() {

    char message[50] = {0};

    while ( true ) {

        gets( message );
        printf( "string \"%s\" received...\n", message );

        // forces the streams to flush
        fflush( stdout );
        fflush( stderr ); // the java program will not write in the error stream, so this line (for this example) is irrelevant

        // if the java program send a "end" command (message here) it will break the while
        if ( !strcmp( "end", message ) ) {
            break;
        }

    }

    return 0;

}

Java Receiver (equal the C program)

import java.util.*;

public class MessageReceiver {

    public static void main( String[] args ) {

        Scanner scan = new Scanner( System.in );

        while ( true ) {

            String message = scan.nextLine();
            System.out.printf( "string \"%s\" received...\n", message );

            System.out.flush();
            System.err.flush();

            if ( message.equals( "end" ) ) {
                break;
            }

        }

    }

}

Java Sender

import java.io.*;
import java.util.*;

public class Sender {

    /**
     * @param args the command line arguments
     */
    public static void main( String[] args ) {
        new Sender().execute();
    }

    public void execute() {

        try {

            // executes the command (the C executable)
            Process process = Runtime.getRuntime().exec( "MessageReceiver.exe" );

            // or, executes the MessageReceiver class
            //Process process = Runtime.getRuntime().exec( "java MessageReceiver" );

            // create the stream gobblers, one for the input stream and one for the
            // error stream. these gobblers will consume these streams.
            StreamGobbler sgInput = new StreamGobbler(
                    process.getInputStream(), "input" );
            StreamGobbler sgError = new StreamGobbler(
                    process.getErrorStream(), "error" );

            // creates a thread for each stream gobbler and start them
            new Thread( sgInput ).start();
            new Thread( sgError ).start();

            // creates a PrintWriter using the process output stream
            PrintWriter writer = new PrintWriter( process.getOutputStream() );

            // preparing to read user input
            Scanner scan = new Scanner( System.in );

            while ( true ) {

                System.out.println( "Send a command: " );
                String command = scan.nextLine();

                // sends the command to the process
                // simulating an user input (note the \n)
                writer.write( command );
                writer.write( "\n" );
                writer.flush();

                // if the command is end, finalizes this app too
                if ( command.equals( "end" ) ) {
                    break;
                }

            }

        } catch ( IOException ioe ) {
            ioe.printStackTrace();
        }

    }

    /**
     * Threads to consume the process streams.
     * Based in the implementation presented here:
     * http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1
     *
     * @author David Buzatto
     */
    private class StreamGobbler implements Runnable {

        private InputStream is;
        private String type;
        private FileWriter fw;

        public StreamGobbler( InputStream is, String type ) {
            this.is = is;
            this.type = type;
        }

        public StreamGobbler( InputStream is, String type, File file )
                throws IOException {
            this.is = is;
            this.type = type;
            this.fw = new FileWriter( file );
        }

        @Override
        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader( is );
                BufferedReader br = new BufferedReader( isr );
                String line = null;
                while ( ( line = br.readLine() ) != null ) {
                    if ( fw != null ) {
                        fw.write( line + "\n" );
                    } else {
                        System.out.println( type + ">" + line );
                    }
                }
                if ( fw != null ) {
                    fw.close();
                }
            } catch ( IOException ioe ) {
                ioe.printStackTrace();
            }
        }
    }

}

To run the code, compile the C program or the MessageReceiver class. Put the executables in the same folder of your Sender class, compiles it and run. The "end" command will finish the receiver and the sender.

Take a look in this article too: http://www.javaworld.com/jw-12-2000/jw-1229-traps.html

这篇关于向控制台应用程序发送命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 01:00