서버-클라이언트가 있는 Java NIO(비차단 I/O) 예제 – java.nio.ByteBuffer 및 channel.Selector – Java NIO Vs. IO
게시 됨: 2021-08-06
Java NIO
는 내가 가장 좋아하는 주제입니다. 저는 지난 2년 동안 NIO와 함께 일해 왔으며 프로덕션 환경에서 이 코드를 자유롭게 사용할 수 있는 독자들을 위해 간단한 Server-Client code
를 공유하고 싶습니다.
JDK 1.4부터 NIO는 모든 Java 프로그래머가 사용자 정의 네이티브 코드를 처리하지 않고도 초고속 입출력을 구현할 수 있도록 만들어졌습니다. NIO는 내부적으로 모든 운영 체제에서 버퍼를 비우고 채우는 단순 I/O와 비교하여 java.nio.buffer
라이브러리를 사용합니다.
이 튜토리얼에서는 java.nio.channels
및 java.nio.channels.Selector
라이브러리를 살펴보겠습니다.
-
channels
은 파일 및 소켓과 같은 I/O 작업을 수행할 수 있는 엔터티에 대한 연결을 나타냅니다. 다중화, 비차단 I/O 작업을 위한 선택기를 정의 합니다. - 이 클래스의
open method
를 호출하여selector
를 만들 수 있으며, 이 메서드는 시스템의 기본 선택기 공급자를 사용하여 새 선택기를 만듭니다.

below questions
이 있는 경우 올바른 위치에 있습니다.
- Java NIO를 시작하는 방법
- Java NIO 및 Java NIO 튜토리얼이란 무엇입니까?
- 비동기 자바 NIO
- java nio 패키지의 정확한 용도는 무엇입니까?
- 자바 NIO 튜토리얼
- Java NIO로 고성능 I/O를 구현하는 방법
시작하자:
1 단계
-
port 1111
에서 연결을 여는CrunchifyNIOServer.java
생성 -
isAcceptable()
을 사용하여 채널이 새 소켓 연결을 수락할 준비가 되었는지 확인합니다.- 그렇다면 연결하십시오
-
isReadable()
을 사용하여 채널이 읽을 준비가 되었는지 확인합니다.- 그렇다면 – 버퍼에서 읽고 Eclipse 콘솔에서 인쇄
- 성을 얻으면 "crunchify"
- 긴밀한 연결
2 단계
-
port 1111
에서 서버에 연결을 시도하는CrunchifyNIOClient.java
를 만듭니다. - 5개의 회사 이름으로 ArrayList 생성
- ArrayList를 반복하고 각 companyName을 서버로 보냅니다.
- 작업 완료 후 연결 닫기
이 Java 코드를 살펴보십시오.
서버 코드 – CrunchifyNIOServer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
package crunchify . com . tutorials ; 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 . util . Iterator ; import java . util . Set ; /** * @author Crunchify.com * Java NIO (Non-blocking I/O) with Server-Client Example - java.nio.ByteBuffer and channels.Selector * This is CrunchifyNIOServer.java */ public class CrunchifyNIOServer { @ SuppressWarnings ( "unused" ) public static void main ( String [ ] args ) throws IOException { // Selector: A multiplexor of SelectableChannel objects. // A selector may be created by invoking the open method of this class, which will use the system's default selector provider to create a new selector. // A selector may also be created by invoking the openSelector method of a custom selector provider. A selector remains open until it is closed via its close method. Selector selector = Selector . open ( ) ; // selector is open here // ServerSocketChannel: A selectable channel for stream-oriented listening sockets. // A server-socket channel is created by invoking the open method of this class. // It is not possible to create a channel for an arbitrary, pre-existing ServerSocket. ServerSocketChannel crunchifySocket = ServerSocketChannel . open ( ) ; // InetSocketAddress: This class implements an IP Socket Address (IP address + port number) It can also be a pair (hostname + port number), // in which case an attempt will be made to resolve the hostname. // If resolution fails then the address is said to be unresolved but can still be used on some circumstances like connecting through a proxy. InetSocketAddress crunchifyAddr = new InetSocketAddress ( "localhost" , 1111 ) ; // Binds the channel's socket to a local address and configures the socket to listen for connections crunchifySocket . bind ( crunchifyAddr ) ; // Adjusts this channel's blocking mode. crunchifySocket . configureBlocking ( false ) ; int ops = crunchifySocket . validOps ( ) ; // SelectionKey: A token representing the registration of a SelectableChannel with a Selector. // A selection key is created each time a channel is registered with a selector. // A key remains valid until it is cancelled by invoking its cancel method, by closing its channel, or by closing its selector. SelectionKey selectKy = crunchifySocket . register ( selector , ops , null ) ; // Infinite loop.. // Keep server running while ( true ) { log ( "I'm a server and I'm waiting for new connection and buffer select..." ) ; // Selects a set of keys whose corresponding channels are ready for I/O operations selector . select ( ) ; // token representing the registration of a SelectableChannel with a Selector Set < SelectionKey > crunchifyKeys = selector . selectedKeys ( ) ; Iterator < SelectionKey > crunchifyIterator = crunchifyKeys . iterator ( ) ; while ( crunchifyIterator . hasNext ( ) ) { SelectionKey myKey = crunchifyIterator . next ( ) ; // Tests whether this key's channel is ready to accept a new socket connection if ( myKey . isAcceptable ( ) ) { SocketChannel crunchifyClient = crunchifySocket . accept ( ) ; // Adjusts this channel's blocking mode to false crunchifyClient . configureBlocking ( false ) ; // Operation-set bit for read operations crunchifyClient . register ( selector , SelectionKey . OP_READ ) ; log ( "Connection Accepted: " + crunchifyClient . getLocalAddress ( ) + "\n" ) ; // Tests whether this key's channel is ready for reading } else if ( myKey . isReadable ( ) ) { SocketChannel crunchifyClient = ( SocketChannel ) myKey . channel ( ) ; // ByteBuffer: A byte buffer. // This class defines six categories of operations upon byte buffers: // Absolute and relative get and put methods that read and write single bytes; // Absolute and relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array; ByteBuffer crunchifyBuffer = ByteBuffer . allocate ( 256 ) ; crunchifyClient . read ( crunchifyBuffer ) ; String result = new String ( crunchifyBuffer . array ( ) ) . trim ( ) ; log ( "Message received: " + result ) ; if ( result . equals ( "Crunchify.com" ) ) { crunchifyClient . close ( ) ; log ( "\nIt's time to close connection as we got last company name 'Crunchify'" ) ; log ( "\nServer will keep running. Try running client again to establish new connection" ) ; } } crunchifyIterator . remove ( ) ; } } } private static void log ( String str ) { System . out . println ( str ) ; } } |
클라이언트 코드 – CrunchifyNIOClient.java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package crunchify . com . tutorials ; import java . io . IOException ; import java . net . InetSocketAddress ; import java . nio . ByteBuffer ; import java . nio . channels . SocketChannel ; import java . util . ArrayList ; /** * @author Crunchify.com * Java NIO (Non-blocking I/O) with Server-Client Example - java.nio.ByteBuffer and channels.Selector * This is CrunchifyNIOClient.java */ public class CrunchifyNIOClient { public static void main ( String [ ] args ) throws IOException , InterruptedException { InetSocketAddress crunchifyAddr = new InetSocketAddress ( "localhost" , 1111 ) ; // selectable channel for stream-oriented connecting sockets SocketChannel crunchifyClient = SocketChannel . open ( crunchifyAddr ) ; log ( "Connecting to Server on port 1111..." ) ; ArrayList <String> companyDetails = new ArrayList <String> ( ) ; // create a ArrayList with companyName list companyDetails . add ( "Facebook" ) ; companyDetails . add ( "Twitter" ) ; companyDetails . add ( "IBM" ) ; companyDetails . add ( "Google" ) ; companyDetails . add ( "Crunchify" ) ; for ( String companyName : companyDetails ) { byte [ ] message = new String ( companyName ) . getBytes ( ) ; ByteBuffer buffer = ByteBuffer . wrap ( message ) ; crunchifyClient . write ( buffer ) ; log ( "sending: " + companyName ) ; buffer . clear ( ) ; // wait for 2 seconds before sending next message Thread . sleep ( 2000 ) ; } // close(): Closes this channel. // If the channel has already been closed then this method returns immediately. // Otherwise it marks the channel as closed and then invokes the implCloseChannel method in order to complete the close operation. crunchifyClient . close ( ) ; } private static void log ( String str ) { System . out . println ( str ) ; } } |
서버 측 결과:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
I 'm a server and I' m waiting for new connection and buffer select . . . Connection Accepted : / 127.0.0.1 : 1111 I 'm a server and <meta charset="utf-8"/>I' m waiting for new connection and buffer select . . . Message received : Facebook < meta charset = "utf-8" / > I 'm a server and <meta charset="utf-8"/>I' m waiting for new connection and buffer select . . . Message received : Twitter < meta charset = "utf-8" / > I 'm a server and <meta charset="utf-8"/>I' m waiting for new connection and buffer select . . . Message received : IBM < meta charset = "utf-8" / > I 'm a server and <meta charset="utf-8"/>I' m waiting for new connection and < a href = "https://crunchify.com/how-to-remove-duplicate-elements-from-csv-or-any-other-file-in-java/" target = "_blank" rel = "noreferrer noopener" > buffer < / a > select . . . Message received : Google < meta charset = "utf-8" / > I 'm a server and <meta charset="utf-8"/>I' m waiting for new connection and buffer select . . . Message received : Crunchify It 's time to <a href="https://crunchify.com/json-manipulation-in-java-examples/" target="_blank" rel="noreferrer noopener">close connection</a> as we got last company name ' Crunchify ' Server will keep running. Try running client again to establish new connection <meta charset="utf-8"/>I' m a server and < meta charset = "utf-8" / > I ' m waiting for new connection and buffer select . . . |
클라이언트 측 결과:
1 2 3 4 5 6 |
Connecting to Server on port 1111... sending : Facebook sending : Twitter sending : IBM sending : Google sending : Crunchify |
몇 가지 자주 묻는 질문:
- 클라이언트에서 어떻게 지속적인 연결을 유지합니까?
-
socket.setKeepAlive(true);
클라이언트 측에서 연결을 유지합니다.
-
- 서버에 보낸 메시지에 대한 응답을 어떻게 읽습니까? 서버는 10초마다 메시지를 계속 생성합니다. 내 요청에 대한 응답을 읽기만 하면 됩니다. 내가 이해하는 바에 따르면 TCP는 레코드 끝 대신 데이터를 "스트리밍"합니다.
- 클라이언트 서버 통신을 위해서는 프로토콜이 잘 정의되어 있어야 합니다.
readLine()
호출은 모든 데이터가 반환될 때까지 차단되므로 사용하지 마십시오.Try reading bytes from the stream until -1 is returned.
- 클라이언트 서버 통신을 위해서는 프로토콜이 잘 정의되어 있어야 합니다.
작동하는지 알려주세요.
