如何通过Java Socket发送命令并接收对OSGi控制台的响应?

时间:2011-09-20 16:08:57

标签: java sockets osgi

我想在另一台计算机上运行OSGi框架(在main方法中)。所以我想知道有没有办法从其他计算机连接到OSGi控制台并管理捆绑包?

我认为使用java.net.Socket会有所帮助,这就是我实现的方法。我用了2个线程。一个用于处理用户输入流,另一个用于处理OSGi Console响应。这是第一个线程(处理用户输入流):

    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控制台?

2 个答案:

答案 0 :(得分:1)

你正在使用阻止io,因此你的内部while循环将从不完成,直到套接字关闭。你需要2个线程才能阻止io流。 1个线程从stdin读取并写入套接字输出流,另一个线程从套接字输入流读取并写入stdout。

另外,您可能希望在将userInput发送到osgi控制台之后编写换行符(Scanner.nextLine()吃换行符。)

最后,在使用套接字时,通常不想使用Print *类,因为它们会隐藏IOExceptions。

答案 1 :(得分:0)

您可能希望使用其中一个可用的远程shell,而不是构建自己的东西,例如http://felix.apache.org/site/apache-felix-remote-shell.html处的Apache Felix

相关问题