【发布时间】:2012-10-28 01:08:20
【问题描述】:
大家好,我用 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();
}
}
【问题讨论】:
-
也许您应该打印它(
e.printStackTrace()),而不是忽略异常是什么。它会告诉你出了什么问题。 -
您的机器上是否启用了该服务?
-
“无法获得连接的 I/O”也不例外。它只是您捕获异常时自己打印出来的东西。这是没用的。您应该打印出的是 exception 本身。然后你就会知道出了什么问题。
标签: java