WEB开发网
开发学院软件开发Java 在Java中使用NIO进行网络编程 阅读

在Java中使用NIO进行网络编程

 2009-12-29 00:00:00 来源:WEB开发网   
核心提示: 配合Buffer使用Channel与传统模式的编程不用,Channel不使用Stream,在Java中使用NIO进行网络编程(2),而是Buffer,我们来实现一个简单的非阻塞Echo Client:packagecom.cnblogs.gpcuster;importjava.net.InetS

配合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();
 }
}

上一页  1 2 3 4  下一页

Tags:Java 使用 NIO

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接