0

大家好,我用java编写了一个简单的telnet套接字客户端,我正在尝试在windows 7 Pro中连接到localhost上的telnet服务。代码执行良好,但无法打印输出流和输入流,而是代码抛出以下异常:尝试连接到端口 1024 上的主机 localhost 无法获取连接到的 I/O:localhost

有什么我想念的吗???代码如下提前谢谢。

import java.io.*;
import java.net.*;
import java.util.*;
public class telnetClients {
public static void main(String[] args) throws IOException {

    String telnetServer = new String ("localhost");
    int port = 1024;
    if (args.length > 0)
       telnetServer = args[0];
    System.out.println ("Attemping to connect to host " +
            telnetServer + " on port "
                + port);

    Socket ClientSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;

    try {
        ClientSocket = new Socket(telnetServer, port);
            ClientSocket.setSoTimeout(20000);
          //    PrintStream com = new PrintStream(ClientSocket.getOutputStream());
          //    System.out.println(com);
           //    BufferedReader inCom = new BufferedReader(new InputStreamReader                (ClientSocket.getInputStream()));


        out = new PrintWriter(ClientSocket.getOutputStream(), true);
        System.out.println(out);
        in = new BufferedReader(new InputStreamReader(
                                    ClientSocket.getInputStream()));
        String command = in.readLine();
        if(in != null);
        System.out.println(in);

    } catch (UnknownHostException e) {
        System.err.println("Don't know about host: " + telnetServer);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for "
                           + "the connection to: " + telnetServer);
        System.exit(1);
    }

BufferedReader stdIn = new BufferedReader(
         new InputStreamReader(System.in));
              String userInput;

    System.out.println ("Type Message (\"bye\" to quit)");
while ((userInput = stdIn.readLine()) != null) 
       {
    out.println(userInput);

        // end loop
        if (userInput.equals("bye"))
            break;

    System.out.println("echo: " + in.readLine());
   }

out.close();
in.close();
stdIn.close();
ClientSocket.close();
}
}
4

2 回答 2

0

对我有用的样品

public static void main(String[] args) {
    String url = "hostname";
    int port = 8080;
    try (Socket pingSocket = new Socket(url, port)) {
      try (PrintWriter out = new PrintWriter(pingSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(pingSocket.getInputStream()));) {
        out.println("ping");
        System.out.println("Telnet Success: " + in.readLine());
      }
    } catch (IOException e) {
      System.out.println("Telnet Fail: " + e.getMessage());
    }
}
于 2020-07-22T08:44:13.403 回答
-2

我认为您的问题可能是没有启用 Telnet 服务。在 Windows 7 中,您可以在 Windows 功能下的程序和功能(控制面板)中进行检查。

之后,您必须配置端口,因为 TCP 连接的默认端口是 23。您可以使用tlntadmn [\\server] config port=PortNumber

于 2012-10-28T01:16:56.477 回答