JAVA NIO 입문 실례
5778 단어 java NIO
package com.liuc.io;
import java.io.IOException;
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.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;
import org.apache.log4j.Logger;
public class NIOServer extends Thread {
private Logger log=Logger.getLogger(NIOServer.class);
private boolean stop=false;
private String ip="localhost";
private int port=9999;
private Selector selector;
private ByteBuffer buffer=ByteBuffer.allocate(1024);
private Charset gbkCharset = Charset.forName( "GB2312" );
public NIOServer() {
try {
selector=Selector.open();
ServerSocketChannel ssc=ServerSocketChannel.open();
InetSocketAddress address=new InetSocketAddress(ip, port);
//ServerSocket IP
ssc.socket().bind(address);
//
ssc.configureBlocking(false);
//
ssc.register(selector,SelectionKey.OP_ACCEPT);
System.out.println("Listen to port:"+port);
} catch (IOException e) {
log.error(e);
}
}
@Override
public void run() {
System.out.println("deal with request");
while(!stop){
String content="HelloWorld";
try {
int numKeys = selector.select();
Set<SelectionKey> selectionKeys=selector.selectedKeys();
Iterator<SelectionKey> iterator=selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
dealRequest(key,content);
}
} catch (IOException e) {
log.equals(e);
}
}
}
private void dealRequest(SelectionKey key,String contentToSend) {
try {
StringBuffer clientContent=new StringBuffer();
if(key.isAcceptable()){// 。
ServerSocketChannel ssc=(ServerSocketChannel) key.channel();
SocketChannel sc=ssc.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey. OP_READ);
}else if(key.isReadable()) {// 。
SocketChannel sc=(SocketChannel) key.channel();
while(true){//
buffer.clear();
int r=sc.read(buffer);
buffer.flip();
byte[] temp=new byte[r];
if (r<=0) {
break;
}
clientContent.append(gbkCharset.decode(buffer).toString());
}
//
String content=clientContent.toString();
String[] info=content.split(",");//
System.out.println(" :"+content);
sc.register(selector, SelectionKey.OP_WRITE);
}else if(key.isWritable()){//
System.out.println(" "+contentToSend);
buffer.clear();
buffer.put(contentToSend.getBytes());
buffer.flip();
SocketChannel sc = (SocketChannel)key.channel();
sc.write(buffer);
buffer.flip();
//
key.cancel();
sc.close();
}
} catch (IOException e) {
System.out.println(e);
// , Selector
key.cancel();
if(key.channel() != null)
try {
key.channel().close();
log.debug("the client socket is closed!");
//System.out.println("the client socket is closed!");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args){
new NIOServer().start();
}
}
클 라 이언 트:
package com.liuc.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class NIOClient {
/**
* @param args
*/
public static void main(String[] args) {
Socket socket=null;
OutputStream outputStream=null;
InputStream inputStream=null;
try {
socket=new Socket("localhost", 9999);
outputStream=socket.getOutputStream();
String sendContent="HelloWorld";
outputStream.write(sendContent.getBytes());
outputStream.flush();
inputStream=socket.getInputStream();
byte[] bytes=new byte[1024];
int n=inputStream.read(bytes);
System.out.println(new String(bytes));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(inputStream!=null){
inputStream.close();
}
if (outputStream!=null) {
outputStream.close();
}
if (socket!=null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JAVA NIO 입문 실례기본 개념: 참조http://zhangshixi.iteye.com/blog/679959작가 의 시 리 즈 는 NIO 가 효율 성 때문에 서버 의 최 우선 선택 이 되 어 서버 의 응답 효율 을 크게 향상 시 켰 다....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.