public class Telnet { Socket serverSocket; // 连接用socket public OutputStream serverOutput; // 用于网络输出的流 public BufferedInputStream serverInput; // 用于网络输入的流 String host; // 连接服务器的地址 int port; // 连接服务器的端口号 static final int DEFAULT_TELNET_PORT = 23; // telnet的端口号(23号)
// 构造器(1):指定地址和端口号时用 public Telnet(String host, int port) { this.host = host; this.port = port; }
// 定义用于协商的命令 static final byte IAC = (byte) 255; static final byte DONT = (byte) 254; static final byte DO = (byte) 253; static final byte WONT = (byte) 252; static final byte WILL = (byte) 251;
// negotiation 方法 // 利用NVT进行协商通信 static void negotiation(BufferedInputStream in, OutputStream out) throws IOException { byte[] buff = new byte[3]; // 接收命令的数组 while (true) { in.mark(buff.length); if (in.available() >= buff.length) { in.read(buff); if (buff[0] != IAC) { // 协商结束 in.reset(); return; } else if (buff[1] == DO) { // 对于DO命令...... buff[1] = WONT; // 用WONT作为应答 out.write(buff); } } } }
// main方法 // 建立TCP连接,开始处理 public static void main(String[] arg) { try { Telnet t = null; // 由参数个数决定调用哪个构造器 // switch (arg.length) { // case 1: //只指定服务器地址 // t = new Telnet(arg[0]); // break; // case 2: //指定地址和端口 // t = new Telnet(arg[0], Integer.parseInt(arg[1])); // break; // default: //使用方法不正确时 // System.out.println( // "usage:java Telnet <host name> { <port number> } "); // return; // } t = new Telnet("222.211.88.185", 23); t.openConnection(); t.main_proc(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }