Newer
Older
myNWP / src / j2 / EchoClient.java
package j2;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class EchoClient {
    // プログラムの本体main
    public static void main(String[] args) {
        if (args.length < 2) {
            args = new String[2];
            args[0] = "127.0.0.1";
            args[1] = "9999";
        }
        new EchoClient(args[0], args[1]);
    }

    public EchoClient(String address, String strport) {
        // ソケットや入出力用のストリームの宣言
        Socket socket = null;
        DataOutputStream dos = null;
        BufferedReader isbr = null;
        BufferedReader stdinbr = null;

        int port = Integer.parseInt(strport);
        try {
            socket = new Socket(address, port);
            isbr = new BufferedReader(new InputStreamReader(socket.getInputStream())); // サーバからの文字列読み出し

            stdinbr = new BufferedReader(new InputStreamReader(System.in)); // 標準入力からの文字列読み出し

            dos = new DataOutputStream(socket.getOutputStream()); // サーバへの文字列書き出し
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + address);
        } catch (IOException e) {
            System.err.println("Echoサーバ [" + address + ":" + port + "] に接続できませんでした");
            System.exit(1); // 異常終了(エラーで終了)なら1
        }

        // サーバーにメッセージを送る
        if (socket != null && dos != null && isbr != null) {
            try {
                // メッセージを送ります
                dos.writeBytes("HELLO\n");

                // サーバーからのメッセージを受け取り画面に表示します
                String line;
                while ((line = isbr.readLine()) != null) {
                    System.out.println("Server: " + line);
                    if (line.equals("quit"))
                        break;

                    String s = stdinbr.readLine();
                    System.out.println(s);
                    dos.writeBytes(s + "\n");
                }

                // 開いたソケットなどをクローズ
                dos.close();
                isbr.close();
                socket.close();
            } catch (UnknownHostException e) {
                System.err.println("Trying to connect to unknown host: " + e);
            } catch (IOException e) {
                System.err.println("IOException: " + e);
            }
        }
    }
}