在Java中使用NIO进行网络编程
2009-12-29 00:00:00 来源:WEB开发网配合Buffer使用Channel
与传统模式的编程不用,Channel不使用Stream,而是Buffer。我们来实现一个简单的非阻塞Echo Client:
package com.cnblogs.gpcuster;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class TCPEchoClientNonblocking {
public static void main(String args[]) throws Exception {
if ((args.length < 2) || (args.length > 3))// Testforcorrect#ofargs
throw new IllegalArgumentException(
"Parameter(s): <Server> <Word> [<Port>]");
String server = args[0];// ServernameorIPaddress
// ConvertinputStringtobytesusingthedefaultcharset
byte[] argument = args[1].getBytes();
int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;
// Createchannelandsettononblocking
SocketChannel clntChan = SocketChannel.open();
clntChan.configureBlocking(false);
// Initiateconnectiontoserverandrepeatedlypolluntilcomplete
if (!clntChan.connect(new InetSocketAddress(server, servPort))) {
while (!clntChan.finishConnect()) {
System.out.print(".");// Dosomethingelse
}
}
ByteBuffer writeBuf = ByteBuffer.wrap(argument);
ByteBuffer readBuf = ByteBuffer.allocate(argument.length);
int totalBytesRcvd = 0;// Totalbytesreceivedsofar
int bytesRcvd;// Bytesreceivedinlastread
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();
}
}
更多精彩
赞助商链接