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 { public static void main(String[] args) { // ソケットや入出力用のストリームの宣言 Socket socket = null; DataOutputStream dos = null; BufferedReader isbr = null; BufferedReader stdinbr = null; if (args.length < 2) { args = new String[2]; args[0] = "127.0.0.1"; // 接続先アドレス args[1] = "9999"; //ポート番号 } String host = args[0]; int port = Integer.parseInt(args[1]); try { socket = new Socket(host, port); dos = new DataOutputStream(socket.getOutputStream()); isbr = new BufferedReader(new InputStreamReader(socket.getInputStream())); stdinbr = new BufferedReader(new InputStreamReader(System.in)); } catch (UnknownHostException e) { System.err.println("Don't know about host: " + host); } catch (IOException e) { System.err.println("Echoサーバ [" + host+":"+port+"] に接続できませんでした"); } // サーバーにメッセージを送る 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); } } } }