(メモ)ネットワーク通信:TCPは全二重を実現し、クライアントとサービス側はコンソール入力交流を行う


package demo;

import java.io.*;
import java.net.*;

public class Server {
	public static void main(String[] args) {
		try {
			ServerSocket ss = new ServerSocket(1026);
			Socket s = ss.accept();
			OutputStream os = s.getOutputStream();
			DataOutputStream dos = new DataOutputStream(os);
			InputStream is=s.getInputStream();
			DataInputStream dis=new DataInputStream(is);

			new ServerReader(dis).start();
			new ServerWriter(dos).start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
class ServerReader extends Thread{
	private DataInputStream dis;
	public ServerReader(DataInputStream dis) {
		this.dis=dis;
	}
	public void run() {
		String info;
		try {
			info=dis.readUTF();
			System.out.println(" :"+info);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class ServerWriter extends Thread{
	private DataOutputStream dos;
	public ServerWriter(DataOutputStream dos) {
		this.dos=dos;
	}
	public void run() {
		InputStreamReader isr=new InputStreamReader(System.in);
		BufferedReader br=new BufferedReader(isr);
		String info;
		try {
			info=br.readLine();
			dos.writeUTF(info);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
package demo;

import java.io.*;
import java.net.*;

public class Client {
	public static void main(String[] args) {
		try {
			
			Socket s = new Socket("127.0.0.1",1026);
			OutputStream os = s.getOutputStream();
			DataOutputStream dos = new DataOutputStream(os);
			InputStream is=s.getInputStream();
			DataInputStream dis=new DataInputStream(is);

			new ClientReader(dis).start();
			new ClientWriter(dos).start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
class ClientReader extends Thread{
	private DataInputStream dis;
	public ClientReader(DataInputStream dis) {
		this.dis=dis;
	}
	public void run() {
		String info;
		try {
			info=dis.readUTF();
			System.out.println(" :"+info);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
}

class ClientWriter extends Thread{
	private DataOutputStream dos;
	public ClientWriter(DataOutputStream dos) {
		this.dos=dos;
	}
	public void run() {
		InputStreamReader isr=new InputStreamReader(System.in);
		BufferedReader br=new BufferedReader(isr);
		String info;
		try {
			info=br.readLine();
			dos.writeUTF(info);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
}