Newer
Older
myNWP / src / j2 / TimeClient.java
@Motoki Miura Motoki Miura on 13 Nov 2021 1 KB format
package j2;

// 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 {
	// プログラムの本体main
	public static void main(String[] args) {
		Socket csock = null;// サーバ接続用ソケット
		BufferedReader reader = null;
		// 指定のポートに対して,ソケットを作成します
		// オブジェクトinstrを作り,データ読み出しを準備します
		try {
			// readsocket = new Socket(args[0], Integer.parseInt(args[1])) ;
			csock = new Socket("127.0.0.1", 5555); // ローカルホストのサーバに接続するとき
			// csock = new Socket("10.104.89.61", 5555) ;//別ホストのサーバに接続する例(サーバのIPアドレスはip
			// aで調査しておく)
			// csock = new Socket(arg[0], 5555) ; //サーバのIPアドレスをコマンドライン引数で指定する例
			reader = new BufferedReader(new InputStreamReader(csock.getInputStream()));
		} catch (Exception e) {
			System.err.println("ネットワークエラーです");
			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);
		}
	}
}