/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
출처: http://crunchify.com/java-nio-non-blocking-io-with-server-client-example-java-nio-bytebuffer-and-channels-selector-java-nio-vs-io/
Java NIO
is my favorite topic. I have been working with NIO since last 2 years and would like to share simple Server-Client code
for my readers who are free to use this code in their production environment.
Starting JDK 1.4, NIO was created to allow all Java programmers to implement very high-speed input/output without having to deal with custom native code. NIO uses java.nio.buffer
library compare to simple I/O which drains and fills back buffer internally any operating system.
In this tutorial we will go over java.nio.channels
and java.nio.channels.Selector
libraries.
channels
represent connections to entities that are capable of performing I/O operations, such as files and sockets; defines selectors, for multiplexed, non-blocking I/O operations.selector
may be created by invoking theopen method
of this class, which will use the system’s default selector provider to create a new selector.
If you have below questions
then you are at right place:
- How to get started with Java NIO
- What is Java NIO and Java NIO tutorials
- Asynchronous Java NIO
- What is the exact use of java nio package
- Java NIO Tutorial
- How to implement High-Performance I/O with Java NIO
Let’s get started:
Step-1
- Create
CrunchifyNIOServer.java
which opens connection onport 1111
- use
isAcceptable()
to check if channel is ready to accept a new socket connection- If yes – connect it
- use
isReadable()
to check if channel is ready for reading- if yes – read from buffer and print on Eclipse console
- Once you get last company name “crunchify”
- close connection
Step-2
- Create
CrunchifyNIOClient.java
which tries to connect to server onport 1111
- Create ArrayList with 5 company names
- Iterate through ArrayList and send each companyName to server
- Close connection after task finish
Take a look at this Java Code:
Server Code – 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 | 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 * */ public class CrunchifyNIOServer { @SuppressWarnings("unused") public static void main(String[] args) throws IOException { // Selector: multiplexor of SelectableChannel objects Selector selector = Selector.open(); // selector is open here // ServerSocketChannel: selectable channel for stream-oriented listening sockets ServerSocketChannel crunchifySocket = ServerSocketChannel.open(); 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 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 crunchifyBuffer = ByteBuffer.allocate(256); crunchifyClient.read(crunchifyBuffer); String result = new String(crunchifyBuffer.array()).trim(); log("Message received: " + result); if (result.equals("Crunchify")) { 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); } } |
Client Code – 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 | 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 * */ public class CrunchifyNIOClient { public static void main(String[] args) throws IOException, InterruptedException { InetSocketAddress crunchifyAddr = new InetSocketAddress("localhost", 1111); 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); } crunchifyClient.close(); } private static void log(String str) { System.out.println(str); } } |
Result at Server Side:
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 i'm waiting for new connection and buffer select... Message received: Facebook i'm a server and i'm waiting for new connection and buffer select... Message received: Twitter i'm a server and i'm waiting for new connection and buffer select... Message received: IBM i'm a server and i'm waiting for new connection and buffer select... Message received: Google i'm a server and i'm waiting for new connection and buffer select... Message received: Crunchify It's time to close connection as we got last company name 'Crunchify' Server will keep running. Try running client again to establish new connection i'm a server and i'm waiting for new connection and buffer select... |
Result at Client Side:
1 2 3 4 5 6 | Connecting to Server on port 1111... sending: Facebook sending: Twitter sending: IBM sending: Google sending: Crunchify |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
출처: https://examples.javacodegeeks.com/core-java/nio/java-nio-socket-example/
This article introduces the
class and its basic usage. This class is defined in the java.nio package.1. Standard Java sockets
Socket programming involves two systems communicating with one another. In implementations prior to NIO, Java TCP client socket code is handled by the java.net.Socket class. A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes,
and , that implement the client side of the connection and the server side of the connection, respectively. The below image illustrates the nature of this communication:A socket is basically a blocking input/output device. It makes the thread that is using it to block on reads and potentially also block on writes if the underlying buffer is full. Therefore, different threads are required if the server has many open sockets. From a simplistic perspective, the process of a blocking socket communication is as follows:
- Create a , specifying a port to listen on.
- Invoke the ServerSocket’s method to listen on the configured port for a client connection.
- When a client connects to the server, the method returns a through which the server can communicate with the client: an is obtained to read from the client and an to write to the client.
2. Nonblocking SocketChannel with java.nio
With the standard java sockets, if the server needed to be scalable, the socket had to be passed to another thread for processing so that the server could continue listening for additional connections, meaning call the ServerSocket’s
method again to listen for another connection.A
3. Example
The following example shows the use of
for creating a simple echo server, meaning it echoes back any message it receives.3.1. The Server code
From the above code:
- In the
- In the
Finally, the
method associates the selector to the socket channel.The second parameter represents the type of the registration. In this case, we use
, which means the selector merely reports that a client attempts a connection to the server. Other possible options are: , which will be used by the client; ; and .
After that, the method is used on line 67, which blocks the execution and waits for events recorded on the selector in an infinite loop. method on line 54, the server is created as nonBlocking, the server socket is retrieved and bound to the specified port: - The selector waits for events and creates the keys. According to the key-types, an opportune operation is performed. There are four possible types for a key:
- Acceptable: the associated client requests a connection.
- Connectable: the server accepted the connection.
- Readable: the server can read.
- Writeable: the server can write.
- If an acceptable key is found, the
- After receiving a readable key from the client, the
and the client’s transmitted data are echoed on System.out:
is called on line 107 which reads from the socket channel. A byte buffer is allocated for reading from the channel
3.2. The Client code
- In the above client code, each client thread creates a socket channel on the server’s host address on line 12:
- On line 19, a String array is created to be transmitted to the server using the previously created socket. The data contain also each thread’s name for distinguishing the sender:
- For each string message a buffer is created on line 24:
and each message is written to the channel from the given buffer on line 25:
3.3. The output
4. Download Java Source Code
This was an example of
You can download the full source code of this example here: SocketExampleNio.zip
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
출처: https://gist.github.com/Botffy/3860641
Because nio is non-blocking, so doesn't require additional threads. A socket-based chat would require as many threads as there are users, adding a significant overhead, while a nio chat would always need but one thread, making it a lot more scalable, as the overhead of threading may get really significant.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
'프로그래밍 관련 > 네트워크, 통신' 카테고리의 다른 글
중국의 어떤 서버 개발자의 디비 설계 (0) | 2020.09.17 |
---|---|
게임 gamedevforever님의 네트워크 게임 튜토리얼 관련 모음 (0) | 2020.09.17 |
[SOCKET-FAQ] 2. 클라이언트와 서버 양쪽에 관한 질문 (TCP/SOCK_STREAM) (0) | 2020.09.17 |
[C#] TCP/IP, 소켓 통신 관련 (0) | 2019.03.04 |
자바 서버 어플리케이션 개발 기반 코드(Boilerplate code) 작성하기 (0) | 2016.05.17 |
why to use nio for doing a chatapplication...when we can simply do it using socket programming easily ?