Java NIO 簡單例子__Java

來源:互聯網
上載者:User

伺服器端:

package nioT;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 NIOServer1 {// 本地字元集private static final String LocalCharSetName = "UTF-8";// 本機伺服器監聽的連接埠private static final int Listenning_Port = 8888;// 緩衝區大小private static final int Buffer_Size = 1024;// 逾時時間,單位毫秒private static final int TimeOut = 3000;public static void main(String[] args) throws IOException {// 建立一個在本地連接埠進行監聽的服務Socket通道.並設定為非阻塞方式ServerSocketChannel serverChannel = ServerSocketChannel.open();serverChannel.socket().bind(new InetSocketAddress(Listenning_Port));serverChannel.configureBlocking(false);// 建立一個選取器並將serverChannel註冊到它上面Selector selector = Selector.open();serverChannel.register(selector, SelectionKey.OP_ACCEPT);while (true) {// 等待某個通道就緒if (selector.select(TimeOut) == 0) {System.out.println(".");continue;}// 獲得就緒通道的鍵迭代器Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();// 使用迭代器進行遍曆就緒通道while (keyIter.hasNext()) {SelectionKey key = keyIter.next();// 這種情況是有用戶端串連過來,準備一個clientChannel與之通訊if (key.isAcceptable()) {SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept();clientChannel.configureBlocking(false);clientChannel.register(selector, SelectionKey.OP_READ,ByteBuffer.allocate(Buffer_Size));}// 用戶端有寫入時if (key.isReadable()) {// 獲得與用戶端通訊的通道SocketChannel clientChannel = (SocketChannel) key.channel();// 得到並重設緩衝區的主要索引值ByteBuffer buffer = (ByteBuffer) key.attachment();buffer.clear();// 讀取資訊獲得讀取的位元組數long bytesRead = clientChannel.read(buffer);if (bytesRead == -1) {// 沒有讀取到內容的情況clientChannel.close();} else {// 將緩衝區準備為資料傳出狀態buffer.flip();// 將獲得位元組字串(使用Charset進行解碼)String receivedString = Charset.forName(LocalCharSetName).newDecoder().decode(buffer).toString();// 控制台列印出來System.out.println("接收到資訊:" + receivedString);// 準備發送的文本String sendString = "你好,用戶端. 已經收到你的資訊" + receivedString;// 將要發送的字串編碼(使用Charset進行編碼)後再進行封裝buffer = ByteBuffer.wrap(sendString.getBytes(LocalCharSetName));// 發送回去clientChannel.write(buffer);// 設定為下一次讀取或是寫入做準備key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);}}keyIter.remove();}}}}

用戶端:

package nioT;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.net.Socket;import java.net.UnknownHostException;import java.util.Scanner;public class NIOClient1Test {public static void main(String[] args) throws UnknownHostException,IOException {Socket s = new Socket("localhost", 8888);InputStream inStream = s.getInputStream();OutputStream outStream = s.getOutputStream();// 輸出PrintWriter out = new PrintWriter(outStream, true);out.println("getPublicKey你好。");out.flush();s.shutdownOutput();// 輸出結束// 輸入Scanner in = new Scanner(inStream);StringBuilder sb = new StringBuilder();while (in.hasNextLine()) {String line = in.nextLine();sb.append(line);}String response = sb.toString();System.out.println("response=" + response);}}

運行結果

服務端:

.接收到資訊:getPublicKey你好。.

用戶端:

response=你好,用戶端. 已經收到你的資訊getPublicKey你好。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.