diff --git a/src/j2/TimeClient.java b/src/j2/TimeClient.java new file mode 100644 index 0000000..2615b23 --- /dev/null +++ b/src/j2/TimeClient.java @@ -0,0 +1,51 @@ +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) ; + 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) ; + } + } +} \ No newline at end of file diff --git a/src/j2/TimeServer.java b/src/j2/TimeServer.java new file mode 100644 index 0000000..24dac7e --- /dev/null +++ b/src/j2/TimeServer.java @@ -0,0 +1,54 @@ +package j2; +// 時刻を答えるサーバプログラムNetclock.java +// このプログラムはポート番号6000番で動作するサーバです +// クライアントからの接続に対し,時刻を返します +// このプログラムを停止させるにはコントロールCを入力してください +// 使い方java Netclock + +// ライブラリの利用 +import java.io.IOException; +import java.io.PrintStream; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.Date; + +// TimeServerクラス +class TimeServer{ + public static void main(String args[]){ + ServerSocket ssock = null ;// サーバ用ソケット + Socket sock ;// ソケットの読み書き用オブジェクト + PrintStream os; + String outstr ;// 出力データを格納する文字列 + Date d ;// 日付時刻処理用オブジェクト + + try{ + // サーバソケットの作成 + ssock = new ServerSocket() ; + ssock.bind(new InetSocketAddress("127.0.0.1", 5555)); + // サーバ側の処理の繰り返し + while(true){ + sock = ssock.accept() ;//接続がくるまで待つ + System.out.println("accepted (client has connected)"); + os = new PrintStream(sock.getOutputStream()); + // 出力用データの作成 + d = new Date() ; + outstr = "\n" + + "Hello, this is Netclock server." + + "\n" + d.toString() + "\n" + + "Thank you." + "\n"; + System.out.println("(Server-side message) "+ outstr); + // データの出力 + os.println(outstr); + os.flush(); + os.close(); + // 接続終了 + sock.close() ; + } + } catch(IOException e){ + System.out.println("*** Exception ***"); + System.out.println(e); + System.exit(1) ; + } + } +} \ No newline at end of file