1. 程式人生 > >Java Telnet客戶端

Java Telnet客戶端

1.第三方庫commons-net-*.jar

開啟Download Apache Commons Net下載jar包。

2.telnet 客戶端

private void connectToServer(String server) {
    TelnetClient telnetClient = new TelnetClient("VT220");
    try {
        telnetClient.connect(server);

        InputStream remoteInput = telnetClient.getInputStream();
        OutputStream remoteOutput = telnetClient.getOutputStream();

        // ReadThread執行緒監聽輸入,並輸出到System.err
        ReadThread readThread = new ReadThread(remoteInput);
        readThread.start();

        String line = null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(remoteOutput);

        while ((line = reader.readLine()) != null) {
            if (line.equals("exit")) {
                break;
            }
            pw.println(line);
            pw.flush();
            System.err.println("request: " + line);
        }
        pw.close();

        readThread.pause();
        readThread.join();			
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (telnetClient.isConnected()) {
            try {
                telnetClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

private static class ReadThread extends Thread {
    private InputStream mInput;
    private boolean mStopped;

    public ReadThread(InputStream input) {
        mInput = input;
    }

    @Override
    public void run() {				
        try {
            byte[] buffer = new byte[1024];
            while (!mStopped) {
                int len = mInput.read(buffer);
                if (len != -1) {
                    System.err.print(new String(buffer, 0, len, "GBK"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mInput != null) {
                try {
                    mInput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void pause() {
        mStopped = true;
    }

}

相關文章
Java Ftp客戶端
Windows下搭建Ftp伺服器
Java Telnet客戶端
Windows下搭建Telnet伺服器