NioSocket簡單復(fù)習(xí)
創(chuàng)新互聯(lián)建站憑借專業(yè)的設(shè)計(jì)團(tuán)隊(duì)扎實(shí)的技術(shù)支持、優(yōu)質(zhì)高效的服務(wù)意識(shí)和豐厚的資源優(yōu)勢(shì),提供專業(yè)的網(wǎng)站策劃、成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、網(wǎng)站優(yōu)化、軟件開發(fā)、網(wǎng)站改版等服務(wù),在成都10余年的網(wǎng)站建設(shè)設(shè)計(jì)經(jīng)驗(yàn),為成都上千余家中小型企業(yè)策劃設(shè)計(jì)了網(wǎng)站。重要概念
NioSocket里面的三個(gè)重要概念:Buffer、Channel、Selector
使用步驟
使用NioSocket實(shí)現(xiàn)通信大概如以下步驟:
實(shí)現(xiàn)HTTP
創(chuàng)建HttpServer類作為程序的主要入口
public class HttpServer { public static void main(String[] args) throws Exception{ ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress((8080))); serverSocketChannel.configureBlocking(false); Selector selector = Selector.open(); // It must be ACCEPT, or it will throw exception serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while(true){ if (selector.select(3000) == 0){ continue; } IteratorkeyIter = selector.selectedKeys().iterator(); while (keyIter.hasNext()){ SelectionKey key = keyIter.next(); new Thread(new HttpHandler(key)).run(); keyIter.remove(); } } } }