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

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

// Telnetクラス
public class Telnet implements Runnable {
	byte[] buff = new byte[1024];//配列の定義
	char[] cbuff = new char[1024];//配列の定義
	Socket socket = null ;// サーバ接続用ソケット
	OutputStream outstr = null;// データ出力用オブジェクト
	DataInputStream din = null;// データ読み取り用オブジェクト
	boolean cont = true ;
	Thread thread = null;
	static Telnet telnet = null;

	// プログラムの本体main
	public static void main(String[] args){
		Telnet.telnet = new Telnet();
		Telnet.telnet.connect(args);
	}
	
	public void connect(String[] args) {
		// 指定のポートに対して,ソケットを作成します
		// 入出力のストリームを作り,データ読み出しを準備します
		try{
			socket = new Socket(args[0], Integer.parseInt(args[1])) ;
			outstr = socket.getOutputStream() ; //サーバへの送信用
			din = new DataInputStream(socket.getInputStream()) ;
			thread = new Thread(this);
			thread.start();
			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) ;
					
					int dn = din.read(buff);
					System.out.println(dn);

					
				}
				// 以下は例外処理です
				catch(Exception e){
					// 例外時はプログラムを終了します
					System.exit(1);
				}
			}

			
		} catch (Exception e) {
			System.err.println("Network error.") ;
			System.exit(1) ;
		}
	}
		

	@Override
	public void run() {
		while (thread != null) {
			try {
//				int n = din.read(buff);
//				System.out.println(n);
//				if (n > 0) {
//					System.out.write(buff);
//					System.out.flush();
//				}
				Thread.sleep(1000);
				System.out.println("hoge");
			}
			catch(Exception e){
				// 読み出し終了時にループも終了
				thread = null ;
			}
		}
		try {
			din.close() ;
		} catch(Exception e) {
			System.err.println("Close failed.") ;
			System.exit(1) ;
		}
	}
}