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 TimeServer."
+ "\n" + d.toString() + "\n"
+ "Thank you." + "\n";
System.out.println("(Server-side message) "+ outstr);
// データの出力(1回目)
os.println(outstr);
Thread.sleep(1000); // 1秒まつ
os.println(new Date().toString()); // データの出力(2回目)
os.flush();
os.close();
// 接続終了
sock.close() ;
}
} catch(IOException e){
System.out.println("*** Exception ***");
System.out.println(e);
System.exit(1) ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}