Newer
Older
ServerTester / src / main / java / info / istlab / ServerTester / TimeClient.java
package info.istlab.ServerTester;

// TimeClient.java
// ネットワーク上のサーバからデータを受け取り,そのまま画面に出力します
// 使い方java TimeClient DNS 名ポート番号
// 例java TimeClient kiku.fuis.fukui-u.ac.jp 6000

//ライブラリの利用
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

// TimeClientクラス
public class TimeClient {
	public static void main(String[] args) {
		if (args.length < 2) {
			System.err.println("Usage: java TimeClient <port> <address>");
			System.exit(1);
		}
		int port = Integer.parseInt(args[0]);
		String address = args[1];
		new TimeClient(port, address);
	}
	public TimeClient(int port, String address) {
		Socket socket = null;// サーバ接続用ソケット
		BufferedReader reader = null;
		address = address.replace("/","");

		// 指定のポートに対して,ソケットを作成します
		// オブジェクトinstrを作り,データ読み出しを準備します
		try {
			socket = new Socket(address, port); // 第2引数は文字列を整数に変換して渡す
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (Exception e) {
			System.err.println("サーバ [" + address + ":" + port + "] に接続できませんでした");
			System.exit(1); // 異常終了(エラーで終了)なら1
		}

		// データの終了まで,以下のループを繰り返します
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				System.out.println("[Reply] " + line);
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		// コネクションを閉じます
		try {
			reader.close();
		} catch (Exception e) {
			// ネットワーククローズ失敗です
			System.err.println("ネットワークのエラーです");
			System.exit(1);
		}
	}
}