totem3
6/28/2012 - 9:23 AM

初echo server

初echo server

package jp.takhirata.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {
	private InetSocketAddress address;
	public EchoServer(InetSocketAddress address) {
		this.address = address;
	}
	
	public static void main(String[] args) {
		int port = 8080;
		InetSocketAddress address = new InetSocketAddress(port);
		EchoServer es = new EchoServer(address);
		try {
			es.run();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run() throws IOException {
		ServerSocket ss = new ServerSocket();
		ss.bind(this.address);
		
		Socket s = ss.accept();
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), "UTF-8"));
		
		while(true) {
			String str = reader.readLine();
			if (str == null) {
								
			} else if (str.equals("exit")) {
				break;
			} else {
				writer.write(str + "¥r¥n");
				writer.flush();
			}
		}
		reader.close();
		writer.close();
	}
}