java telnet socket客户端

时间:2012-10-28 01:08:20

标签: java

大家好我在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();
}
}

2 个答案:

答案 0 :(得分: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());
    }
}

答案 1 :(得分:-2)

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

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

执行此操作