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 ThreadEchoClient implements Runnable { BufferedReader isbr = null; Thread thread = null; public ThreadEchoClient(Socket socket) { try { isbr = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (IOException e) { e.printStackTrace(); } thread = new Thread(this); thread.start(); } @Override public void run() { // サーバーからのメッセージを受け取り画面に表示します String line; try { while ((line = isbr.readLine()) != null) { System.out.println("Server: " + line); if (line.equals("quit")) break; } } catch (IOException e) { e.printStackTrace(); } finally { System.exit(0); } } public static void main(String[] args) { // ソケットや入出力用のストリームの宣言 Socket socket = null; DataOutputStream dos = null; BufferedReader stdinbr = null; // ポート9999番を開く String host = "localhost"; try { socket = new Socket(host, 9999); dos = new DataOutputStream(socket.getOutputStream()); 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("Couldn't get I/O for the connection to: "+host); } // サーバーにメッセージを送る if (socket != null && dos != null ) { new ThreadEchoClient(socket); try { // メッセージを送ります dos.writeBytes("HELLO\n"); // 標準入力(キーボード)からのメッセージを送信します while (true) { String s = stdinbr.readLine(); dos.writeBytes(s+"\n"); } // 開いたソケットなどをクローズ // dos.close(); // socket.close(); } catch (UnknownHostException e) { System.err.println("Trying to connect to unknown host: " + e); } catch (IOException e) { System.err.println("IOException: " + e); } } } }