Java和telnet - java.net.SocketException:管道损坏

时间:2015-05-23 13:31:43

标签: java osgi telnet

我有一个osgi框架,我想在oder中通过telnet连接它,只发送一个命令 - shutdown。这就是为什么我不想使用像apache commons telnet这样的telnet库。 我的代码:

System.out.println("I am stopping....");
Socket socket=new Socket("localhost",6666);
String command="shutdown";
PrintWriter pw = new PrintWriter( socket.getOutputStream(), true);
pw.print(command);
pw.flush();
socket.close();
pw.close();

它关闭了osgi但是在osgi框架方面我得到了:

org.apache.felix.shell.remote [27] TerminalPrintStream::print()
java.net.SocketException: Broken pipe
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
    at org.apache.felix.shell.remote.TerminalPrintStream.print(TerminalPrintStream.java:48)
    at org.apache.felix.shell.remote.TerminalPrintStream.println(TerminalPrintStream.java:63)
    at org.apache.felix.shell.remote.Shell.startFelixShell(Shell.java:130)
    at org.apache.felix.shell.remote.Shell.run(Shell.java:86)
    at java.lang.Thread.run(Thread.java:745)

如何解决?

编辑1:
但是,以下代码无任何异常(apache commons net)。

TelnetClient telnet=new TelnetClient();
        try {
            telnet.connect("localhost", 6666);
            BufferedInputStream input = new BufferedInputStream(telnet.getInputStream());  
            PrintStream output = new PrintStream(telnet.getOutputStream());  
            output.println("shutdown");
            output.flush();
        } catch (IOException ex) {
            Logger.getLogger(ProgramManager.class.getName()).log(Level.SEVERE, null, ex);
        }

1 个答案:

答案 0 :(得分:1)

您不应在发送命令后立即关闭流,因为在这种情况下服务器无法应答并抛出异常。您应该读取套接字的流,直到它被服务器关闭。一旦远程shell模块停止,它将立即关闭。

根据您的代码:

System.out.println("I am stopping....");
String command="shutdown";
try (Socket socket=new Socket("localhost",6666)) {
  OutputStream out = socket.getOutputStream();
  InputStream in = socket.getInputStream();
  out.write(command.getBytes(Charset.defaultCharset()));

  // Wait until server closes the stream. Could be enhanced with some timeout
  BufferedReader reader = new BufferedReader(new InputStreamReader(in, 
      Charset.defaultCharset())));
  String line = reader.readLine();
  while (line != null) {
    System.out.println(line);
  }
}