while (totalBytesRcvd < argument.length) {
if (writeBuf.hasRemaining()) {
clntChan.write(writeBuf);
}
if ((bytesRcvd = clntChan.read(readBuf)) == -1) {
throw new SocketException("Connection closed prematurely");
}
totalBytesRcvd += bytesRcvd;
System.out.print(".");// Dosomethingelse
}
System.out.println("Received:" + // converttoStringperdefaultcharset
new String(readBuf.array(), 0, totalBytesRcvd));
clntChan.close();
}
}
在Java中使用NIO进行网络编程(2)
时间:2011-04-03 博客园 逖靖寒
这段代码使用ByteBuffer来保存读写的数据。通过clntChan.configureBlocking (false); 设置后,其中的connect,read,write操作都不回阻塞,而是立刻放回结果。
使用Selector
Selector的可以从所有的被注册到自己Channel中找到需要服务的实例。
我们来实现Echo Server。
首先,定义一个接口:
package com.cnblogs.gpcuster;
import java.nio.channels.SelectionKey;
import java.io.IOException;
public interface TCPProtocol {
void handleAccept(SelectionKey key) throws IOException;
void handleRead(SelectionKey key) throws IOException;
void handleWrite(SelectionKey key) throws IOException;
}
我们的Echo Server将使用这个接口。然后我们实现Echo Server:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
public class TCPServerSelector {
private static final int BUFSIZE = 256;// Buffersize(bytes)
private static final int TIMEOUT = 3000;// Waittimeout (milliseconds)
public static void main(String[] args) throws IOException {
if (args.length < 1) {// Testforcorrect#ofargs
throw new IllegalArgumentException("Parameter (s):<Port>...");
}
// Createaselectortomultiplexlisteningsocketsandconnections
Selector selector = Selector.open();
// Createlisteningsocketchannelforeachportandregisterselector
for (String arg : args) {
ServerSocketChannel listnChannel = ServerSocketChannel.open();
listnChannel.socket().bind(
new InetSocketAddress(Integer.parseInt(arg)));
listnChannel.configureBlocking(false);// mustbenonblockingtoregister
// Registerselectorwithchannel.Thereturnedkeyisignored
listnChannel.register(selector, SelectionKey.OP_ACCEPT);
}
// Createahandlerthatwillimplementtheprotocol
TCPProtocol protocol = new EchoSelectorProtocol(BUFSIZE);
while (true) {// Runforever,processingavailableI/Ooperations
// Waitforsomechanneltobeready(ortimeout)
if (selector.select(TIMEOUT) == 0) {// returns#ofreadychans
System.out.print(".");
continue;
}
// GetiteratoronsetofkeyswithI/Otoprocess
Iterator<SelectionKey> keyIter =
|