Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write Java NIO code

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to write Java NIO code". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to write Java NIO code.

Java Code:

Import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; 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.util.Iterator; import java.util.Set; public class NIOServer {/ * identification number * / private int flag = 0 / * buffer size * / private int BLOCK = 4096; / * accept data buffer * / private ByteBuffer sendbuffer = ByteBuffer.allocate (BLOCK); / * send data buffer * / private ByteBuffer receivebuffer = ByteBuffer.allocate (BLOCK); private Selector selector; public NIOServer (int port) throws IOException {/ / Open server socket channel ServerSocketChannel serverSocketChannel = ServerSocketChannel.open () / / the server is configured as non-blocking serverSocketChannel.configureBlocking (false); / / retrieve the server socket associated with this channel ServerSocket serverSocket = serverSocketChannel.socket (); / / bind serverSocket.bind for service (new InetSocketAddress (port)); / / find Selector selector = Selector.open () through the open () method / / Register to selector and wait for serverSocketChannel.register (selector, SelectionKey.OP_ACCEPT); System.out.println ("Server Start----8888:") } / / listens to private void listen () throws IOException {while (true) {/ / Select a set of keys, and the corresponding channel has selector.select () open; / / returns the selected key set of this selector. Set selectionKeys = selector.selectedKeys (); Iterator iterator = selectionKeys.iterator (); while (iterator.hasNext ()) {SelectionKey selectionKey = iterator.next (); iterator.remove (); handleKey (selectionKey) } / / process request private void handleKey (SelectionKey selectionKey) throws IOException {/ / accept request ServerSocketChannel server = null; SocketChannel client = null; String receiveText; String sendText; int count=0; / / Test whether the channel of this key is ready to accept a new socket connection. If (selectionKey.isAcceptable ()) {/ / returns the channel for which this key was created. Server = (ServerSocketChannel) selectionKey.channel (); / / accepts a connection to this channel socket. The socket channel returned by this method, if any, will be in blocking mode. Client = server.accept (); / / is configured as non-blocking client.configureBlocking (false); / / registers to selector and waits for a connection to client.register (selector, SelectionKey.OP_READ);} else if (selectionKey.isReadable ()) {/ / returns the channel for which this key was created. Client = (SocketChannel) selectionKey.channel (); / / clear the buffer for the next read receivebuffer.clear (); / / read the data sent by the server into the buffer count = client.read (receivebuffer); if (count > 0) {receiveText = new String (receivebuffer.array (), zero count) System.out.println ("Server accepts client data--:" + receiveText); client.register (selector, SelectionKey.OP_WRITE);}} else if (selectionKey.isWritable ()) {/ / clear the buffer for next write to sendbuffer.clear () / / returns the channel for which this key was created. Client = (SocketChannel) selectionKey.channel (); sendText= "message from server--" + flag++; / / enter data sendbuffer.put (sendText.getBytes ()) into the buffer; / / reset each flag of the buffer because the data flag has been changed inside. If you want to read data from it and send it to the server, reset sendbuffer.flip (). / / output to channel client.write (sendbuffer); System.out.println ("server sends data to client--:" + sendText); client.register (selector, SelectionKey.OP_READ) }} / * * @ param args * @ throws IOException * / public static void main (String [] args) throws IOException {/ / TODO Auto-generated method stub int port = 8888; NIOServer server = new NIOServer (port); server.listen ();}}

Java Code:

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.util.Iterator; import java.util.Set; public class NIOClient {/ * identification number * / private static int flag = 0; / * buffer size * / private static int BLOCK = 4096 / * accept data buffer * / private static ByteBuffer sendbuffer = ByteBuffer.allocate (BLOCK); / * send data buffer * / private static ByteBuffer receivebuffer = ByteBuffer.allocate (BLOCK); / * server-side address * / private final static InetSocketAddress SERVER_ADDRESS = new InetSocketAddress ("localhost", 1111) Public static void main (String [] args) throws IOException {/ / TODO Auto-generated method stub / / Open socket channel SocketChannel socketChannel = SocketChannel.open (); / / set to non-blocking mode socketChannel.configureBlocking (false); / / Open selector Selector selector = Selector.open () / / register connection server socket action socketChannel.register (selector, SelectionKey.OP_CONNECT); / / connect socketChannel.connect (SERVER_ADDRESS); / / allocate buffer size memory Set selectionKeys; Iterator iterator; SelectionKey selectionKey; SocketChannel client; String receiveText; String sendText Int count=0; while (true) {/ / Select a set of keys whose corresponding channels are ready for the Istroke O operation. / / this method performs a selection operation in blocking mode. Selector.select (); / / returns the selected key set for this selector. SelectionKeys = selector.selectedKeys (); / / System.out.println (selectionKeys.size ()); iterator = selectionKeys.iterator (); while (iterator.hasNext ()) {selectionKey = iterator.next (); if (selectionKey.isConnectable ()) {System.out.println ("client connect") Client = (SocketChannel) selectionKey.channel (); / / determines whether a connection operation is in progress on this channel. / / complete the connection process of the socket channel. If (client.isConnectionPending ()) {client.finishConnect (); System.out.println ("complete the connection!"); sendbuffer.clear (); sendbuffer.put ("Hello,Server" .getBytes ()); sendbuffer.flip () Client.write (sendbuffer);} client.register (selector, SelectionKey.OP_READ);} else if (selectionKey.isReadable ()) {client = (SocketChannel) selectionKey.channel () / / clear the buffer for the next read receivebuffer.clear (); / / read the data sent by the server to the buffer count=client.read (receivebuffer) If (count > 0) {receiveText = new String (receivebuffer.array (), 0score count); System.out.println ("client accepts server-side data--:" + receiveText); client.register (selector, SelectionKey.OP_WRITE) }} else if (selectionKey.isWritable ()) {sendbuffer.clear (); client = (SocketChannel) selectionKey.channel (); sendText = "message from client--" + (flag++); sendbuffer.put (sendText.getBytes ()) / / reset each flag of the buffer, because the put data flag has been changed. If you want to read data from it and send it to the server, reset sendbuffer.flip (); client.write (sendbuffer); System.out.println ("client sends data to server--:" + sendText). Client.register (selector, SelectionKey.OP_READ);}} selectionKeys.clear () Thank you for your reading, the above is the content of "how to write Java NIO code". After the study of this article, I believe you have a deeper understanding of how to write Java NIO code, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report