最近在做一个远程控制的模块,其中用到了telnet协议,开始用的是apache-net包的telnetclient,但发现问题不少,比较慢,还有就是判断是否read完毕的问题。后来经过讨论打算实现自己的telnet,于是网址打罗了一番,找了一个,但是bug也不少,就开始封装。具体的telnet我已经发过2篇文章了,这里再发布一个深化封装的telnet实现。
仅供参考,可以在windows和linux上运行。
- package baby.net.base;
-
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.InetSocketAddress;
- import java.net.Socket;
- import java.util.ArrayList;
-
- import org.apache.log4j.Logger;
-
- public class TelnetBase {
- private static final byte SB = (byte) 250;
- private static final byte SE = (byte) 240;
- private static final byte WILL = (byte) 251;
- private static final byte WONT = (byte) 252;
- private static final byte DO = (byte) 253;
- private static final byte DONT = (byte) 254;
- private static final byte IAC = (byte) 255;
- private static final byte ECHO = (byte) 1;
- private static final byte IS = (byte) 0;
- private static final byte SUPPRESS = (byte) 3;
- private static final byte TT = (byte) 24;
- private InputStream is;
- private OutputStream os;
- private Socket client;
- private byte[] readBuffer = new byte[20 * 1024];
- private int miniReadIntervalMillSec = 3000;
- private int connectTimeout = 1000;
- private int maxReadTimeout = 5000;
-
- public static String[] failTags = { "Failed", "fail", "incorrect" };
- public static String[] loginTags = { "$", "#", ">", "ogin", "@" };
- public static String[] commondEndTags= { "$", "#", ">"};
- public static String[] allTags = { "Failed", "fail", "incorrect", "$", "#",
- ">", "ogin", "@" };
-
- private String ip;
- private int port = 23;
-
- Logger logger = Logger.getLogger(getClass());
-
-
-
- public TelnetBase(String ip) {
-
- this(ip, 23);
-
- }
-
-
-
- public TelnetBase(String ip, int port) {
- this.ip = ip;
- this.port = port;
- }
-
-
- public String connect() throws Exception {
- try {
-
- client = new Socket();
- client.connect(new InetSocketAddress(ip, port), connectTimeout);
- client.setSoTimeout(miniReadIntervalMillSec);
- is = client.getInputStream();
- os = client.getOutputStream();
- } catch (Exception e) {
- this.close();
- throw new Exception(e);
- }
- return readKeyWords("ogin:");
- }
-
-
-
- public String recieveEcho() throws IOException {
-
- int len = is.read(this.readBuffer);
-
- ArrayList<Byte> bsList = new ArrayList<Byte>();
- ArrayList<Byte> cmdList = new ArrayList<Byte>();
- for (int i = 0; i < len; i++) {
- int b = this.readBuffer[i] & 0xff;
- if (b != 255) {
- if (b == ‘\n‘ || b == ‘\0‘) {
- continue;
- }
- bsList.add((byte) b);
- continue;
- }
- cmdList.add(IAC);
- switch (this.readBuffer[++i] & 0xff) {
- case 251:
- if ((readBuffer[++i] & 0xff) == 1) {
- cmdList.add(DO);
- cmdList.add(ECHO);
- } else if ((readBuffer[i] & 0xff) == 3) {
- cmdList.add(DO);
- cmdList.add(SUPPRESS);
-
- } else {
- cmdList.add(DONT);
- cmdList.add(readBuffer[i]);
- }
- break;
- case 253:
- if ((readBuffer[++i] & 0xff) == 24) {
- cmdList.add(WONT);
- cmdList.add(TT);
- } else if ((readBuffer[i] & 0xff) == 1) {
- cmdList.add(WILL);
- cmdList.add(ECHO);
- } else {
- cmdList.add(WONT);
- cmdList.add(readBuffer[i]);
- }
- break;
- case 250:
- cmdList.add(SB);
- if ((readBuffer[++i] & 0xff) == 24
- && (readBuffer[++i] & 0xff) == 1) {
- cmdList.add(TT);
- cmdList.add(IS);
- cmdList.add((byte) ‘V‘);
- cmdList.add((byte) ‘T‘);
- cmdList.add((byte) ‘1‘);
- cmdList.add((byte) ‘0‘);
- cmdList.add((byte) ‘0‘);
- }
- break;
- case 240:
- cmdList.add(SE);
- break;
- case 252:
- cmdList.add(DONT);
- cmdList.add(readBuffer[++i]);
- break;
- case 254:
- cmdList.add(WONT);
- cmdList.add(readBuffer[++i]);
- break;
- }
- }
-
- if (cmdList.size() > 0) {
- byte[] writeBuffer = new byte[cmdList.size()];
- for (int i = 0; i < cmdList.size(); i++) {
- writeBuffer[i] = cmdList.get(i);
- }
- os.write(writeBuffer);
- }
-
-
- int size = bsList.size();
- String str = "";
- if (size > 0) {
- byte[] bs = new byte[size];
- for (int i = 0; i < size; i++) {
- bs[i] = bsList.get(i).byteValue();
- }
- str = new String(bs, "gbk");
- } else {
-
- if (cmdList.size() > 0) {
- str = recieveEcho();
- }
- }
-
- return str;
- }
-
- private void log(int len, ArrayList<Byte> cmdList) {
- logger.debug("read===== ");
- for (int i = 0; i < len; i++) {
- logger.debug(readBuffer[i] & 0xff);
- logger.debug(" ");
- }
-
- if (cmdList.size() > 0) {
- logger.debug("write==== ");
- for (int i = 0; i < cmdList.size(); i++) {
- logger.debug(cmdList.get(i) & 0xff);
- logger.debug(" ");
- }
-
- }
- }
-
-
- public String sendUserName(String name) throws Exception {
- name += "\r\n";
- os.write(name.getBytes());
-
- return readKeyWords("assword");
- }
-
-
- public String sendUserPwd(String pwd) throws Exception {
- pwd += "\r\n";
- os.write(pwd.getBytes());
-
- return readKeyWords(allTags);
- }
-
-
- public String sendCmd(String cmd, String... keyWords) throws Exception {
-
- return sendCmd(cmd,false,keyWords);
- }
-
- public String sendCmd(String cmd,boolean excludeCommandCheck, String... keyWords) throws Exception {
- os.write((cmd + "\r\n").getBytes());
-
- if(!excludeCommandCheck){
- return readKeyWords(cmd,maxReadTimeout,keyWords);
- }else{
- return readKeyWords(keyWords);
- }
- }
-
-
- public String sendCommand(String cmd) throws Exception {
-
- return sendCommand(cmd,false);
- }
-
- public String sendCommand(String cmd,boolean excludeCommandCheck) throws Exception {
-
- os.write((cmd + "\r\n").getBytes());
- if(!excludeCommandCheck){
- return readKeyWords(cmd,maxReadTimeout,commondEndTags);
- }else{
- return readKeyWords(commondEndTags);
- }
- }
-
-
- public String sendCommand(String cmd, long timeOut) throws Exception {
-
- return sendCommand(cmd,timeOut, false);
- }
-
- public String sendCommand(String cmd, long timeOut,boolean excludeCommandCheck) throws Exception {
- os.write((cmd + "\r\n").getBytes());
-
- if(!excludeCommandCheck){
- return readKeyWords(cmd,timeOut, commondEndTags);
- }else{
- return readKeyWords(timeOut, commondEndTags);
- }
-
- }
-
-
- public String sendCmd(String cmd, long timeOut, String... keyWords)
- throws Exception {
-
- return sendCmd(cmd,false,timeOut, keyWords);
- }
-
- public String sendCmd(String cmd, boolean excludeCommandCheck,long timeOut, String... keyWords)
- throws Exception {
- os.write((cmd + "\r\n").getBytes());
- if(!excludeCommandCheck){
- return readKeyWords(cmd,timeOut, keyWords);
- }else{
- return readKeyWords(timeOut, keyWords);
- }
-
- }
-
-
-
- public void close() {
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (os != null) {
- try {
- os.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (client != null) {
- try {
- client.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
-
-
- public String readKeyWords(String... keyWords) {
-
- return this.readKeyWords(maxReadTimeout, keyWords);
-
- }
-
-
-
- public String readKeyWords(long timeOut, String... keyWords) {
- String rv = "";
- long nextTime = 0;
- long endTime = System.currentTimeMillis() + timeOut;
- do {
- try {
- String _rv = this.recieveEcho();
- rv += _rv;
- } catch (IOException e) {
-
- nextTime = endTime - System.currentTimeMillis();
- }
- } while (!this.findKeyWord(keyWords, rv) && nextTime >= 0);
- if (nextTime < 0)
- System.err.println("Read TimeOut...Echo:\n" + rv);
- return rv;
-
- }
-
-
- public String readKeyWords(String command,long timeOut, String... keyWords) {
- String rv = "";
- long nextTime = 0;
- long endTime = System.currentTimeMillis() + timeOut;
- do {
- try {
- String _rv = this.recieveEcho();
- rv += _rv;
- } catch (IOException e) {
-
- nextTime = endTime - System.currentTimeMillis();
- }
- } while (!this.findKeyWord(command,keyWords, rv) && nextTime >= 0);
- if (nextTime < 0)
- System.err.println("Read TimeOut...Echo:\n" + rv);
- return rv;
-
- }
-
-
-
- public boolean findKeyWord(String[] keyWords, String str) {
- if (str == null || "".equals(str))
- return false;
- if (keyWords == null || keyWords.length == 0)
- return true;
- for (int i = 0; i < keyWords.length; i++) {
- if (str.indexOf(keyWords[i]) != -1)
- return true;
- }
- return false;
- }
-
-
- public boolean findKeyWord(String command,String[] keyWords, String str) {
- if (str == null || "".equals(str))
- return false;
- if (keyWords == null || keyWords.length == 0)
- return true;
- System.out.println(str);
- if(-1 != str.indexOf(command)){
- str=str.substring(str.indexOf(command)+command.length());
- for (int i = 0; i < keyWords.length; i++) {
- if (str.indexOf(keyWords[i]) != -1)
- return true;
- }
- }
-
-
- return false;
- }
-
-
- public int getMiniReadIntervalMillSec() {
- return miniReadIntervalMillSec;
- }
-
- public void setMiniReadIntervalMillSec(int miniReadIntervalMillSec) {
- this.miniReadIntervalMillSec = miniReadIntervalMillSec;
- }
-
-
- public int getConnectTimeout() {
- return connectTimeout;
- }
-
- public void setConnectTimeout(int connectTimeout) {
- this.connectTimeout = connectTimeout;
- }
-
-
- public int getMaxReadTimeout() {
- return maxReadTimeout;
- }
-
- public void setMaxReadTimeout(int maxReadTimeout) {
- this.maxReadTimeout = maxReadTimeout;
- }
-
- }
http://blog.csdn.net/chaofanwei/article/details/14130179
http://www.iteye.com/topic/284636
关于telnet协议的研究以及用java进行封装实现自己的telnet客户端(转)
原文:http://www.cnblogs.com/softidea/p/4553665.html