NIO系列5:SocketChannel的理解

本文參考至:http://ifeve.com/socket-channel/
在NIO系列4中,采用了SocketChannel作為案例講解Selector,當時我確實看不太懂。現(xiàn)在寫一下SocketChannel的理解:

Java NIO中的SocketChannel是一個連接到TCP網(wǎng)絡(luò)套接字的通道。可以通過以下2種方式創(chuàng)建SocketChannel:
1、打開一個SocketChannel并連接到互聯(lián)網(wǎng)上的某臺服務(wù)器。
2、一個新連接到達ServerSocketChannel時,會創(chuàng)建一個SocketChannel。

這里簡要的介紹一下Channel的讀寫數(shù)據(jù)的方法,其實對于所有的Channel讀寫數(shù)據(jù)的方法都幾乎一樣,都是從Buffer中讀或者寫到Buffer中,下面舉FileChannel和SocketChannel兩個例子:

Reading from a FileChannel:
    ByteBuffer buf = ByteBuffer.allocate(48);
    int bytesRead = inChannel.read(buf);
Reading from a SocketChannel:
    ByteBuffer buf = ByteBuffer.allocate(48);
    int bytesRead = socketChannel.read(buf);
Writing to a SocketChannel:
    String newData = "New String to write to file..." + System.currentTimeMillis();
    ByteBuffer buf = ByteBuffer.allocate(48);
    buf.clear();
    buf.put(newData.getBytes());
    buf.flip();
    while(buf.hasRemaining()) {
        socketchannel.write(buf);
    }
Writing Data to a FileChannel:
String newData = "New String to write to file..." + System.currentTimeMillis();
    ByteBuffer buf = ByteBuffer.allocate(48);
    buf.clear();
    buf.put(newData.getBytes());
    buf.flip();
    while(buf.hasRemaining()) {
        fileChannel.write(buf);
    }

以下代碼模擬了服務(wù)器和客戶端:

服務(wù)器:

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;

public class TCPServer {

    private static final int bufferSize = 1024;
    private static final long timeOut = 3000;// 超時時間
    private static final int listenPort = 1993;// 本地監(jiān)聽端口

    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();
        ServerSocketChannel listenerChannel = ServerSocketChannel.open();// 創(chuàng)建監(jiān)聽通道,專門用來監(jiān)聽指定的本地端口
        listenerChannel.socket().bind(new InetSocketAddress(listenPort));// 將listenerChannel的socket綁定為本地服務(wù)器(IP+prot)綁定
        listenerChannel.configureBlocking(false);
        // 將選擇器綁定到監(jiān)聽信道,只有非阻塞信道才可以注冊選擇器.并在注冊過程中指出該信道可以進行Accept操作
        listenerChannel.register(selector, SelectionKey.OP_ACCEPT);
        TCPProtocolImpl protocol = new TCPProtocolImpl(bufferSize);

        while (true) {
            if (selector.select(timeOut) == 0) {// 監(jiān)聽注冊的通道,當其中有注冊的IO時該函數(shù)返回(3000ms沒有反應(yīng)返回0),操作可以進行,并添加對應(yīng)的SelectorKey
                System.out.println("It haven't I/O now, please wait!");
                continue;
            }

            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                try {
                    SelectionKey key = keyIter.next();
                    if (key.isAcceptable()) {
                        protocol.handleAccept(key);
                    }
                    if (key.isReadable()) {
                        protocol.handleRead(key);
                    }
                } catch (IOException e) {
                    keyIter.remove();
                    continue;
                }
                keyIter.remove();
            }
        }
    }
}

class TCPProtocolImpl{
    private int bufferSize;

    public TCPProtocolImpl() {
        super();
    }

    public TCPProtocolImpl(int bufferSize) {
        super();
        this.bufferSize = bufferSize;
    }

    public void handleAccept(SelectionKey key) throws IOException {
        // 返回創(chuàng)建此鍵的通道,接受客戶端建立連接的請求,并返回SocketChannel對象
        SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept();
        clientChannel.configureBlocking(false);
        // 將clientChannel注冊到服務(wù)端的selector中
        clientChannel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));
    }

    public void handleRead(SelectionKey key) throws IOException {
        // 獲取客戶端通信的通道
        SocketChannel clientChannel = (SocketChannel) key.channel();
        ByteBuffer buffer = (ByteBuffer) key.attachment();
        buffer.clear();
        // 從客戶端通道讀取信息到buffer緩沖區(qū)中(并返回讀到信息的字節(jié)數(shù))
        long bytesRead = clientChannel.read(buffer);
        if (bytesRead == -1) {
            clientChannel.close();
        } else {
            buffer.flip();
            // 將字節(jié)轉(zhuǎn)化為為UTF-8的字符串
            String receivedString = Charset.forName("UTF-8").newDecoder().decode(buffer).toString();
            System.out.println("接收到來自:" + clientChannel.socket().getRemoteSocketAddress() + "發(fā)來的信息:" + receivedString);
            String msgSendToClient = "已接收到你的信息:" + receivedString + "正在處理中";
            buffer = ByteBuffer.wrap(msgSendToClient.getBytes("UTF-8"));
            clientChannel.write(buffer);
            // 設(shè)置為下一次讀取或是寫入做準備
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }
    }
}

客戶端:

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.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

public class TCPClient {

    // 通道選擇器,用于管理客戶端的通道
    private Selector selector;

    // 與服務(wù)器通信的通道
    SocketChannel socketChannel;

    // 要連接的服務(wù)器的IP
    private String hostIp;

    // 要連接的遠程服務(wù)器在監(jiān)聽的端口
    private int hostListenningPort;
    
    static TCPClient client;
    
    static boolean mFlag = true;

    public TCPClient(String hostIp, int hostPort) throws IOException {
        this.hostIp = hostIp;
        this.hostListenningPort = hostPort;
        init();
    }

    private void init() throws IOException {
        // 打開監(jiān)聽通道
        socketChannel = SocketChannel.open(new InetSocketAddress(hostIp, hostListenningPort));
        socketChannel.configureBlocking(false);
        
        // 創(chuàng)建選擇器,并把通道注冊到選擇器中
        selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);
        
        new TCPClientReadThread(selector);
    }
    
    /**
     * 發(fā)送字符串到服務(wù)器
     * @param message
     * @throws IOException
     */
    public void sendMsg(String message) throws IOException{
        ByteBuffer writeBuffer = ByteBuffer.wrap(message.getBytes("UTF-8"));
        socketChannel.write(writeBuffer);
    }
    
    public static void main(String[] args) throws IOException {
        client = new TCPClient("127.0.0.1", 1993);
        new Thread(){
            @Override
            public void run(){
                try{
                    client.sendMsg("test----~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                    while(mFlag){
                        Scanner scan = new Scanner(System.in);
                        String string = scan.next();
                        client.sendMsg(string);
                    }
                }catch (Exception e) {
                    mFlag = false;
                }finally{
                    mFlag = false;
                }
                super.run();
            }
        }.start();
    }
} 

class TCPClientReadThread implements Runnable {
    private Selector selector;

    public TCPClientReadThread(Selector selector) {
        super();
        this.selector = selector;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            while (selector.select() > 0) {// select()方法只能使用一次,用了之后就會自動刪除,每個連接到服務(wù)器的選擇器都是獨立的
                // 遍歷每個有IO操作Channel對應(yīng)的SelectionKey
                for (SelectionKey sk : selector.selectedKeys()) {
                    if (sk.isReadable()) {
                        // 使用NIO讀取Channel中的數(shù)據(jù)
                        SocketChannel sc = (SocketChannel) sk.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sc.read(buffer);
                        buffer.flip();
                        String receivedString = Charset.forName("UTF-8").newDecoder().decode(buffer).toString();
                        System.out.println("接收到來自服務(wù)器:" + sc.socket().getRemoteSocketAddress() + "的信息:" + receivedString);
                        sk.interestOps(SelectionKey.OP_READ);
                    }
                    selector.selectedKeys().remove(sk);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,333評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,491評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,263評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,946評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,708評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,186評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,409評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,939評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,774評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,976評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,209評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,641評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,872評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,650評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,958評論 2 373

推薦閱讀更多精彩內(nèi)容

  • Java NIO(New IO)是從Java 1.4版本開始引入的一個新的IO API,可以替代標準的Java I...
    JackChen1024閱讀 7,564評論 1 143
  • 簡介 Java NIO 是由 Java 1.4 引進的異步 IO.Java NIO 由以下幾個核心部分組成: Ch...
    永順閱讀 1,807評論 0 15
  • 前言: 之前的文章《Java文件IO常用歸納》主要寫了Java 標準IO要注意的細節(jié)和技巧,由于網(wǎng)上各種學習途徑,...
    androidjp閱讀 2,913評論 0 22
  • (轉(zhuǎn)載說明:本文非原創(chuàng),轉(zhuǎn)載自http://ifeve.com/java-nio-all/) Java NIO: ...
    數(shù)獨題閱讀 814評論 0 3
  • 周五老師在一開始為我們解答了printf函數(shù)的一些遺留問題,在這里我想把它記錄下來加深記憶。顯示的換行問題: 在練...
    Tangjiayue92閱讀 149評論 0 0