Newer
Older
NWP / src / j3 / Telnet.java
@Motoki Miura Motoki Miura on 21 Aug 2020 1 KB httpd
package j3;

import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.net.Socket;

// Telnetクラス
public class Telnet {
	// プログラムの本体main
	public static void main(String[] args){
		byte[] buff = new byte[1024];//配列の定義
		Socket socket = null ;// サーバ接続用ソケット
		OutputStream outstr = null;// データ出力用オブジェクト
		BufferedInputStream din = null;// データ読み取り用オブジェクト
		boolean cont = true ;
		// 指定のポートに対して,ソケットを作成します
		// 入出力のストリームを作り,データ読み出しを準備します
		try{
			socket = new Socket(args[0], Integer.parseInt(args[1])) ;
			outstr = socket.getOutputStream() ; //サーバへの送信用
			din = new BufferedInputStream(socket.getInputStream()) ;
		} catch (Exception e) {
			System.err.println("Network error.") ;
			System.exit(1) ;
		}
		//
		while (cont) {
			try {
				int n = System.in.read(buff);
				System.out.println(new String(buff));
				if(buff[0] == '.') cont = false ;
				else outstr.write(buff,0,n) ;
			}
			// 以下は例外処理です
			catch(Exception e){
				// 例外時はプログラムを終了します
				System.exit(1);
			}
		}
		// データの終了まで,以下のループを繰り返します
		cont = true ;
		while (cont) {
			try {
				int n = din.read(buff);
				if (n > 0) {
					System.out.println(n);
					System.out.write(buff, 0, n) ;
					System.out.flush();
				}
			}
			catch(Exception e){
				// 読み出し終了時にループも終了
				cont = false ;
			}
		}
		try {
			din.close() ;
		} catch(Exception e) {
			System.err.println("Close failed.") ;
			System.exit(1) ;
		}
	}
}