In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the non-blocking mode of NIO Socket". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what the NIO Socket non-blocking mode is.
Main principles and applications of NIO
NIO has a main class Selector, which is similar to an observer, as long as we tell Selector the socketchannel we need to find out, and we go on to do something else. When something happens, he will notify us, send back a set of SelectionKey, we read these Key, we will get the socketchannel we just registered, and then we read the data from this Channel, rest assured that the package will be able to read it, and then we can process the data.
The internal principle of Selector is actually doing a polling visit to the registered channel, constantly polling (currently only this algorithm). Once a channel is polled that something registered has happened, such as data, he will stand up and report, hand over a key, and let us read the contents of the channel through this key.
The non-blocking Istroke O (NIO) provided by jdk effectively solves the problem of thread overhead in multithreaded servers, but it is a little more complicated in use. The main purpose of using multithreading in NIO is not to allocate independent service threads to respond to each client request, but to improve the service capability by making full use of the processing power and waiting time of multiple CPU.
During this time, I am studying NIO and writing a blog to remember what I have learned. Starting with the simplest Hello World, client multithreading requests the server side, and server receives the name of client and returns the character format of Hello! + name to client. Of course, the practical application is not so simple, it may be to access the file or database to get the information and return it to client. What is the mystery of non-blocking NIO?
Code:
1) server side code
Public class HelloWorldServer {static int BLOCK = 1024; static String name = ""; protected Selector selector; protected ByteBuffer clientBuffer = ByteBuffer.allocate (BLOCK); protected CharsetDecoder decoder; static CharsetEncoder encoder = Charset.forName ("GB2312"). NewEncoder (); public HelloWorldServer (int port) throws IOException {selector = this.getSelector (port); Charset charset = Charset.forName ("GB2312"); decoder = charset.newDecoder () } / / get Selector protected Selector getSelector (int port) throws IOException {ServerSocketChannel server = ServerSocketChannel.open (); Selector sel = Selector.open (); server.socket () .bind (new InetSocketAddress (port)); server.configureBlocking (false); server.register (sel, SelectionKey.OP_ACCEPT); return sel } / / listening port public void listen () {try {for (;;) {selector.select (); Iterator iter = selector.selectedKeys () .iterator (); while (iter.hasNext ()) {SelectionKey key = (SelectionKey) iter.next () Iter.remove (); process (key);} catch (IOException e) {e.printStackTrace () }} / / handle event protected void process (SelectionKey key) throws IOException {if (key.isAcceptable ()) {/ / receive request ServerSocketChannel server = (ServerSocketChannel) key.channel (); SocketChannel channel = server.accept (); / / set non-blocking mode channel.configureBlocking (false) Channel.register (selector, SelectionKey.OP_READ);} else if (key.isReadable ()) {/ / read message SocketChannel channel = (SocketChannel) key.channel (); int count = channel.read (clientBuffer); if (count > 0) {clientBuffer.flip (); CharBuffer charBuffer = decoder.decode (clientBuffer) Name = charBuffer.toString (); / / System.out.println (name); SelectionKey sKey = channel.register (selector, SelectionKey.OP_WRITE); sKey.attach (name);} else {channel.close () } clientBuffer.clear ();} else if (key.isWritable ()) {/ / write event SocketChannel channel = (SocketChannel) key.channel (); String name = (String) key.attachment (); ByteBuffer block = encoder.encode (CharBuffer. Wrap ("Hello!" + name)) Channel.write (block); / / channel.close ();}} public static void main (String [] args) {int port = 8888; try {HelloWorldServer server = new HelloWorldServer (port); System.out.println ("listening on" + port) Server.listen ();} catch (IOException e) {e.printStackTrace ();}
2) client side code
Public class HelloWorldClient {static int SIZE = 10; static InetSocketAddress ip = new InetSocketAddress ("localhost", 8888); static CharsetEncoder encoder = Charset.forName ("GB2312"). NewEncoder (); static class Message implements Runnable {protected String name; String msg = ""; public Message (String index) {this.name = index } public void run () {try {long start = System.currentTimeMillis (); / / Open Socket channel SocketChannel client = SocketChannel.open (); / / set to non-blocking mode client.configureBlocking (false) / / Open the selector Selector selector = Selector.open (); / / register the connection server socket action client.register (selector, SelectionKey.OP_CONNECT); / / connect client.connect (ip) / / allocate memory ByteBuffer buffer = ByteBuffer.allocate (8 * 1024); int total = 0; _ FOR: for (;;) {selector.select (); Iterator iter = selector.selectedKeys () .iterator () While (iter.hasNext ()) {SelectionKey key = (SelectionKey) iter.next (); iter.remove () If (key.isConnectable ()) {SocketChannel channel = (SocketChannel) key .channel (); if (channel.isConnectionPending ()) channel.finishConnect () Channel. Write (encoder. Encode (CharBuffer.wrap (name); channel.register (selector, SelectionKey.OP_READ) } else if (key.isReadable ()) {SocketChannel channel = (SocketChannel) key .channel (); int count = channel.read (buffer) If (count > 0) {total + = count; buffer.flip (); while (buffer.remaining () > 0) {byte b = buffer.get () Msg + = (char) b;} buffer.clear ();} else {client.close () Break _ FOR;} double last = (System.currentTimeMillis ()-start) * 1.0 / 1000 System.out.println (msg + "used time:" + last + "s."); msg = "";} catch (IOException e) {e.printStackTrace () } public static void main (String [] args) throws IOException {String names [] = new String [SIZE]; for (int index = 0; index < SIZE; index++) {names [index] = "jeff [" + index+ "]"; new Thread (new Message (namesindex)) .start () At this point, I believe you have a deeper understanding of "what NIO Socket non-blocking mode is". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.