簡體   English   中英

如何通過Java Socket發送命令並接收對OSGi控制台的響應?

[英]How to send commands and receive responses to OSGi console via a Java Socket?

我想在另一台計算機上(以一種主要方法)運行OSGi框架。 所以我想知道有什么方法可以從另一台計算機連接到OSGi控制台並管理捆綁軟件嗎?

我認為也許使用java.net.Socket會有所幫助,這就是我實現的方式。 我用了2個線程。 一個用於處理用戶輸入流,另一個用於處理OSGi控制台響應。 這是第一個線程(處理用戶輸入流):

    configMap.put("osgi.console", "6666");
    Framework fwk = ff.newFramework(configMap);
    try {
        fwk.start();
    } catch (BundleException e) {
        e.printStackTrace();
    }

//__________________________________________________________________//

    try {
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        Socket socket = new Socket(InetAddress.getByName("0.0.0.0"), 6666);
        printlnInfo("Socket has been created: " + socket.getInetAddress() + ":" + socket.getPort());
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        ConsoleOutputReciever fr = new ConsoleOutputReciever();
        new Thread(fr).start();
        while (true) {
            String userInput = "";
            while ((userInput = stdIn.readLine()) != null) {
                System.out.println("--> " + userInput);
                out.write(userInput + "\n");
                out.flush();
            }
            System.out.println("2");
        }
    } catch (Exception e1) {
        e1.printStackTrace();
    }

這是第二個線程(處理OSGi控制台響應):

public class ConsoleOutputReciever implements Runnable {

public Scanner in = null;

@Override
public void run() {
    printlnInfo("ConsoleOutputReciever Started");
    try {
        Socket socket = new Socket(InetAddress.getByName("0.0.0.0"), 6666);
        printlnInfo("Socket has been created: " + socket.getInetAddress() + ":" + socket.getPort());
        String osgiResponse = "";
        in = new Scanner(socket.getInputStream());
        try {
            while (true) {
                in = new Scanner(socket.getInputStream());
                while (in.hasNext()) {
                    System.out.println("-- READ LOOP");
                    osgiResponse = in.nextLine();
                    System.out.println("-- " + osgiResponse);
                }
            }
        } catch (IllegalBlockingModeException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

   }
}

但是我只收到OSGi控制台的第一響應。 像這樣:


-閱讀循環

-

-閱讀循環

ss

-> SS


關於此問題的任何想法或遠程連接到OSGi控制台的任何其他方式?

您正在使用阻塞io,因此您的內部while循環將永遠不會結束,直到關閉套接字為止。 您需要2個線程來阻止io流來完成此操作。 1個線程從stdin讀取並寫入套接字輸出流,另一個線程從socket輸入流讀取並寫入stdout。

同樣,您可能希望在將userInput發送到osgi控制台后寫換行符(Scanner.nextLine()使用換行符)。

最后,在使用套接字時,通常不希望使用Print *類,因為它們會隱藏IOExceptions。

除了構建自己的東西外,您可能希望使用可用的遠程外殼之一,例如,Apache Felix的http://felix.apache.org/site/apache-felix-remote-shell.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM