简体   繁体   中英

Java and telnet - java.net.SocketException: Broken pipe

I have an osgi framework and I want to connect to it via telnet in oder to send only one command - shutdown. That's why I don't want to use telnet libs like apache commons telnet. My code:

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

It shutdowns osgi but on the side of osgi framework I get:

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)

How to fix it?

EDIT 1:
However the following code works without any exception (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);
        }

You should not close the stream as soon as you sent the command as in this case the server cannot answer and throw the exception. You should read the stream of the socket until it is closed by the server. It will be closed as soon as the remote shell module is stopped.

Based on your code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM