NIO Socket 단순 통신 인스턴스

4155 단어
이곳은 단지 보존할 뿐, 기능은 계속 완벽해질 것이다.
현재 기능은
서버: 클라이언트의 요청을 받고 클라이언트에게 문자열을 되돌려줍니다.
클라이언트: 서버에 연결하고 서버가 되돌아오는 데이터를 읽습니다
서버:
package com.zf.test02;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class SelectorServer {

	private Selector selector  ;

	private ServerSocketChannel serverChannel ;

	private ByteBuffer buff ;

	public SelectorServer(){
		try {
			selector = Selector.open() ;
			serverChannel = ServerSocketChannel.open() ;
			serverChannel.configureBlocking(false) ;
			serverChannel.socket().bind(new InetSocketAddress(8888));
			serverChannel.register(selector, SelectionKey.OP_ACCEPT) ;
			buff = ByteBuffer.allocate(1024) ;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void openServer() throws IOException{

		while(true){
			System.out.println(" select ...");
			int keys = selector.select() ;
			if(keys > 0){
				Iterator<SelectionKey> itKeys = selector.selectedKeys().iterator() ;
				while(itKeys.hasNext()){
					SelectionKey key = itKeys.next() ;
					if(key.isAcceptable()){
						System.out.println(" ,Accept ...");
						ServerSocketChannel ss = (ServerSocketChannel)key.channel();
						SocketChannel clientChannel = ss.accept();
						System.out.println(" " + clientChannel.socket().getRemoteSocketAddress() + " ");
						writeMessageToClient(clientChannel , "Hello Welcome!");
						System.out.println(" " + clientChannel.socket().getRemoteSocketAddress() + " ");
					}
					itKeys.remove();
				}

			}

		}





	}

	public void writeMessageToClient(SocketChannel clientChannel , String message){
		try {
			buff.clear() ;
			buff.put(message.getBytes("UTF-8"))  ;
			buff.flip() ;  
			clientChannel.write(buff) ;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws IOException {

		SelectorServer ss = new SelectorServer() ;

		ss.openServer(); 

	}

}

클라이언트:
package com.zf.test02;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class SelectorClient {

	private SocketChannel socketChannel ;
	private InetSocketAddress serverAddress;
	private Selector selector  ;
	private ByteBuffer buf = ByteBuffer.allocate(1024) ;

	public SelectorClient(){
		try {
			serverAddress = new
					InetSocketAddress(InetAddress.getByName("127.0.0.1"), 8888) ;
			socketChannel = SocketChannel.open(serverAddress) ;
			socketChannel.configureBlocking(false);
			selector = Selector.open() ;
			socketChannel.register(selector, 
					SelectionKey.OP_READ) ;
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void connectServer() throws IOException{  
		while(true	){
			int keys = selector.select() ;
			System.out.println(" ...");
			if(keys > 0){
				Iterator<SelectionKey> itKeys =    
						selector.selectedKeys().iterator() ;
				while(itKeys.hasNext()){

					SelectionKey key = itKeys.next() ;

					if(key.isReadable()){
						readMessageFromChannel() ;
					}
					itKeys.remove();
				}
			}
		}

	}

	public void readMessageFromChannel() throws IOException{
		buf.clear() ;
		socketChannel.read(buf) ;
		buf.flip();
		System.out.println(" :" + new String(buf.array() ,
				0 , buf.limit() , "UTF-8"));  
	}

	public static void main(String[] args) throws IOException {

		SelectorClient client = new SelectorClient();
		client.connectServer(); 


	}

}

좋은 웹페이지 즐겨찾기