자바 NIO-5 비 차단 프로 그래 밍 NIO 기반 의 예
Server:
/**
*
*
* @author Joeson
*
*/
public class MyServer
{
public static void main(String args[]) throws Exception
{
MyServer server = new MyServer(8080);
server.listen();
}
//
private ByteBuffer send = ByteBuffer.allocate(1024);
private ByteBuffer receive = ByteBuffer.allocate(1024);
public int port = 0;
ServerSocketChannel ssc = null;
Selector selector = null;
public MyServer(int port) throws Exception
{
//
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//
serverSocketChannel.configureBlocking(false);
//
ServerSocket serverSocket = serverSocketChannel.socket();
//
serverSocket.bind(new InetSocketAddress(port));
// open() Selector
selector = Selector.open();
// selector,
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server Start----8888:");
//
send.put("data come from server".getBytes());
}
//
private void listen() throws IOException
{
while (true)
{
// ,
selector.select();
// 。
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext())
{
SelectionKey selectionKey = iterator.next();
// remove , selector selectedKeys
iterator.remove();
dealKey(selectionKey);
}
}
}
//
private void dealKey(SelectionKey selectionKey) throws IOException
{
ServerSocketChannel server = null;
SocketChannel client = null;
String receiveText;
String sendText;
int count = 0;
// 。
if (selectionKey.isAcceptable())
{
// 。
server = (ServerSocketChannel) selectionKey.channel();
// ( ) 。
client = server.accept();
//
client.configureBlocking(false);
// selector,
client.register(selector, SelectionKey.OP_READ
| SelectionKey.OP_WRITE);
}
else
if (selectionKey.isReadable())
{
// 。
client = (SocketChannel) selectionKey.channel();
//
receive.clear();
//
client.read(receive);
System.out.println(new String(receive.array()));
selectionKey.interestOps(SelectionKey.OP_WRITE);
}
else
if (selectionKey.isWritable())
{
//
send.flip();
// 。
client = (SocketChannel) selectionKey.channel();
//
client.write(send);
selectionKey.interestOps(SelectionKey.OP_READ);
}
}
}
Client:
/**
*
*
* @author Joeson
*
*/
public class MyClient
{
public static void main(String args[])
{
try
{
MyClient client = new MyClient();
client.work(8085);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
SocketChannel sc = null;
Selector selector = null;
//
ByteBuffer send = ByteBuffer.wrap("data come from client".getBytes());
ByteBuffer receive = ByteBuffer.allocate(1024);
public void work(int port) throws IOException
{
try
{
sc = SocketChannel.open();
selector = selector.open();
//
sc.configureBlocking(false);
sc.connect(new InetSocketAddress("localhost", 8080));
sc.register(selector, SelectionKey.OP_CONNECT|SelectionKey.OP_READ|SelectionKey.OP_WRITE);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// Set<SelectionKey> selectionKeys = null;
while (true)
{
//
if (selector.select() == 0)
{
continue;
}
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext())
{
SelectionKey key = it.next();
//
it.remove();
sc = (SocketChannel) key.channel();
if (key.isConnectable())
{
if (sc.isConnectionPending())
{
// ,
sc.finishConnect();
System.out.println("connect completely");
try
{
sc.write(send);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// sc.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);
}
}
else
if (key.isReadable())
{
try
{
receive.clear();
sc.read(receive);
System.out.println(new String(receive.array()));
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
if (key.isWritable())
{
receive.flip();
try
{
send.flip();
sc.write(send);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}// end while
}// end while(true)
}// end work()
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.