import java.io.*;
import java.net.*;
import java.util.*;
class Server{
public static void main(String args[]){
try{
// ポート番号の取得
int nPort = Integer.parseInt(args[0]);
if( nPort < 1000 || nPort > 65535 )
throw new NumberFormatException();
// サーバーソケット作成
ServerSocket serverSocket = new ServerSocket(nPort);
for( int i = 1 ; true ; i++ ){
// 接続を待機する
Socket sock = serverSocket.accept();
System.out.println(sock.getInetAddress().getHostName() + " から接続されました");
// ストリーム作成
OutputStream os = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
// データ送信
String str1 = "こんにちは、あなたは" + i + "番目のお客様です\n";
String str2 = "ただいま、" + (new Date()).toString() + "です \n";
dos.writeUTF(str1);
dos.writeUTF(str2);
// クローズ
os.close();
sock.close();
}
}catch(NumberFormatException e){
System.err.println("引数はポート番号です。1000〜65535までの数字を設定してください。");
}catch(IndexOutOfBoundsException e){
System.err.println("引数はポート番号です。1000〜65535までの数字を設定してください。");
}catch(IOException e){
System.err.println("入出力エラーです\n" + e);
}catch(Exception e){
System.err.println(e);
}
}
}
import java.io.*;
import java.net.*;
import java.util.*;
class Client{
public static void main(String args[]){
try{
// サーバー名の取得
String strServer = args[0];
// ポート番号の取得
int nPort = Integer.parseInt(args[1]);
if( nPort < 1000 || nPort > 65535 )
throw new NumberFormatException();
// サーバーに接続
Socket sock = new Socket(strServer, nPort);
// ストリーム作成
InputStream is = sock.getInputStream();
DataInputStream ios = new DataInputStream(is);
// データ受信
System.out.print(ios.readUTF());
System.out.println(ios.readUTF());
// クローズ
is.close();
sock.close();
}catch(NumberFormatException e){
System.err.println("引数はサーバー名とポート番号です。");
}catch(IndexOutOfBoundsException e){
System.err.println("引数はサーバー名とポート番号です。");
}catch(UnknownHostException e){
System.err.println("サーバー(" + args[0] + ")が見つかりません");
}catch(IOException e){
System.err.println("入出力エラーです\n" + e);
}catch(Exception e){
System.err.println(e);
}
}
}
|