← Back to Advanced Java Course | Chapter 13: Java NIO | Lesson 5 of 5

Java के Non-blocking Sockets

NIO का SocketChannel और ServerSocketChannel non-blocking network I/O को support करते हैं, एक Selector वाले single thread को एक साथ कई client connections manage करने देते हुए।

Blocking vs Non-blocking Sockets

एक classic java.net.Socket data का इंतज़ार करते हुए calling thread को block करता है, जिसके लिए हर connection के लिए एक dedicated thread चाहिए, जबकि NIO का SocketChannel non-blocking mode में switch किया जा सकता है, एक thread को कई connections service करने देते हुए।

उदाहरण: Blocking vs Non-blocking Sockets

java
import java.nio.channels.SocketChannel;
public class Main {
	public static void main(String[] args) throws Exception {
		SocketChannel channel = SocketChannel.open();
		channel.configureBlocking(false); // one thread can service many such channels
		System.out.println("Non-blocking: " + !channel.isBlocking());
		channel.close();
	}
}

Opening a ServerSocketChannel

ServerSocketChannel, ServerSocket का NIO equivalent है, incoming connections accept करते हुए लेकिन किसी Selector के साथ register होने पर non-blockingly ऐसा करने में सक्षम।

उदाहरण: Opening a ServerSocketChannel

java
import java.nio.channels.ServerSocketChannel;
public class Main {
	public static void main(String[] args) throws Exception {
		ServerSocketChannel server = ServerSocketChannel.open();
		server.bind(new java.net.InetSocketAddress(0));
		server.configureBlocking(false); // can accept non-blockingly when registered with a Selector
		System.out.println("Listening on port " + server.socket().getLocalPort());
		server.close();
	}
}

Registering Channels with a Selector

एक non-blocking channel OP_ACCEPT या OP_READ जैसी किसी specific interest के लिए एक Selector के साथ register होता है, और Selector सिर्फ उन channels को वापस report करता है जो असल में उस operation के लिए तैयार हों।

उदाहरण: Registering Channels with a Selector

java
import java.nio.channels.*;
public class Main {
	public static void main(String[] args) throws Exception {
		Selector selector = Selector.open();
		ServerSocketChannel server = ServerSocketChannel.open();
		server.bind(new java.net.InetSocketAddress(0));
		server.configureBlocking(false);
		server.register(selector, SelectionKey.OP_ACCEPT); // interested in accept events only
		System.out.println("Registered for OP_ACCEPT");
		selector.close();
		server.close();
	}
}

The Selector Event Loop

एक Selector-based server select() call करती एक loop चलाता है, जो तब तक block करती है जब तक कम से कम एक registered channel तैयार न हो, फिर हर event को handle करने के लिए ready set पर iterate करता है, जैसे कोई connection accept करना या उपलब्ध data पढ़ना।

उदाहरण: The Selector Event Loop

java
import java.nio.channels.*;
public class Main {
	public static void main(String[] args) throws Exception {
		Selector selector = Selector.open();
		ServerSocketChannel server = ServerSocketChannel.open();
		server.bind(new java.net.InetSocketAddress(0));
		server.configureBlocking(false);
		server.register(selector, SelectionKey.OP_ACCEPT);
		int ready = selector.selectNow(); // non-blocking check instead of select() for this demo
		System.out.println("Ready channels: " + ready);
		selector.close();
		server.close();
	}
}

Accepting and Reading Client Connections

event loop के अंदर, एक OP_ACCEPT-ready key का मतलब है कि एक नया client accept किया जा सकता है, जबकि एक OP_READ-ready key का मतलब है कि पहले से connected किसी client के पास एक buffer में पढ़े जाने के लिए data इंतज़ार कर रहा है।

उदाहरण: Accepting and Reading Client Connections

java
import java.nio.channels.*;
import java.net.InetSocketAddress;
public class Main {
	public static void main(String[] args) throws Exception {
		ServerSocketChannel server = ServerSocketChannel.open();
		server.bind(new InetSocketAddress(0));
		server.configureBlocking(false);
		// OP_ACCEPT-ready key -> server.accept() returns a new client SocketChannel
		// OP_READ-ready key -> that client channel has data waiting in a buffer
		System.out.println("Server ready to accept on port " + server.socket().getLocalPort());
		server.close();
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. configureBlocking(false) call किए बिना किसी channel को Selector के साथ register करना, जो IllegalBlockingModeException फेंकता है।
  2. key को handle करने के बाद selectedKeys() से न हटाना, जिससे वही event अगले loop पर फिर से process होता है।
  3. यह मान लेना कि एक read पूरा message return करेगा, जबकि एक non-blocking read सिर्फ data का हिस्सा या 0 bytes return कर सकता है।
चैप्टर सारांश
  • Java NIO classic I/O streams के विकल्प के रूप में non-blocking I/O प्रदान करता है।
  • Path और Files API, async file I/O, और WatchService files और directory बदलावों को handle करते हैं।
  • Non-blocking sockets उसी approach को network communication तक बढ़ाते हैं।
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.