java.nio的一个小例子

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.nio.charset.*;
import java.lang.*;


public class NonBlockingServer
{
    public Selector sel = null;
    public ServerSocketChannel server = null;
    public SocketChannel socket = null;
    public int port = 4900;
    String result = null;


    public NonBlockingServer()
    {
  System.out.println("Inside default ctor");
    }
   
 public NonBlockingServer(int port)
    {
  System.out.println("Inside the other ctor");
  port = port;
    }

    public void initializeOperations() throws IOException,UnknownHostException
    {
  System.out.println("Inside initialization");
  sel = Selector.open();
  server = ServerSocketChannel.open();
  server.configureBlocking(false);
  InetAddress ia = InetAddress.getLocalHost();
  InetSocketAddress isa = new InetSocketAddress(ia,port);
  server.socket().bind(isa);
    }
   
 public void startServer() throws IOException
    {
  System.out.println("Inside startserver");
        initializeOperations();
  System.out.println("Abt to block on select()");
  SelectionKey acceptKey = server.register(sel, SelectionKey.OP_ACCEPT ); 
 
  while (acceptKey.selector().select() > 0 )
  { 
    
   Set readyKeys = sel.selectedKeys();
   Iterator it = readyKeys.iterator();

   while (it.hasNext()) {
    SelectionKey key = (SelectionKey)it.next();
    it.remove();
               
    if (key.isAcceptable()) {
     System.out.println("Key is Acceptable");
     ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
     socket = (SocketChannel) ssc.accept();
     socket.configureBlocking(false);
     SelectionKey another = socket.register(sel,SelectionKey.OP_READ|SelectionKey.OP_WRITE);
    }
    if (key.isReadable()) {
     System.out.println("Key is readable");
     String ret = readMessage(key);
     if (ret.length() > 0) {
      writeMessage(socket,ret);
     }
    }
    if (key.isWritable()) {
     System.out.println("THe key is writable");
     String ret = readMessage(key);
     socket = (SocketChannel)key.channel();
     if (result.length() > 0 ) {
      writeMessage(socket,ret);
     }
    }
   }
  }
    }

    public void writeMessage(SocketChannel socket,String ret)
    {
  System.out.println("Inside the loop");

  if (ret.equals("quit") || ret.equals("shutdown")) {
   return;
  }
  File file = new File(ret);
  try
  {
  
   RandomAccessFile rdm = new RandomAccessFile(file,"r");
   FileChannel fc = rdm.getChannel();
   ByteBuffer buffer = ByteBuffer.allocate(1024);
   fc.read(buffer);
   buffer.flip();
   
   Charset set = Charset.forName("us-ascii");
   CharsetDecoder dec = set.newDecoder();
   CharBuffer charBuf = dec.decode(buffer);
   System.out.println(charBuf.toString());
   buffer = ByteBuffer.wrap((charBuf.toString()).getBytes());
   int nBytes = socket.write(buffer);
   System.out.println("nBytes = "+nBytes);
    result = null;
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }

    }
 
    public String readMessage(SelectionKey key)
    {
  int nBytes = 0;
  socket = (SocketChannel)key.channel();
        ByteBuffer buf = ByteBuffer.allocate(1024);
  try
  {
            nBytes = socket.read(buf);
   buf.flip();
   Charset charset = Charset.forName("us-ascii");
   CharsetDecoder decoder = charset.newDecoder();
   CharBuffer charBuffer = decoder.decode(buf);
   result = charBuffer.toString();
    
        }
  catch(IOException e)
  {
   e.printStackTrace();
  }
  return result;
    }

    public static void main(String args[])
    {
  NonBlockingServer nb = new NonBlockingServer();
  try
  {
   nb.startServer();
  }
  catch (IOException e)
  {
   e.printStackTrace();
   System.exit(-1);
  }
  
 }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java NIO(New I/O)是一个可以替代标准 Java I/O API 的 Java API。NIO 提供了更快速、更高效的 I/O 操作方式,也可以进行非阻塞 I/O 操作。 下面是几个 NIO 核心类和接口: - Buffer:缓冲区,用于数据的读取和写入。 - Channel:通道,用于数据的读取和写入。 - Selector:选择器,用于监控多个通道的 I/O 状态,从而实现多路复用。 下面介绍一下 NIO 的主要操作步骤: 1. 创建 Buffer 对象:创建一个 Buffer 对象,用于存储数据。 2. 创建 Channel 对象:创建一个 Channel 对象,用于读取和写入数据。 3. 打开 Channel:打开一个 Channel 对象,并连接到指定的服务器。 4. 将数据写入 Buffer:将需要写入的数据写入到 Buffer 中。 5. 切换 Buffer 模式:将 Buffer 从写模式切换到读模式。 6. 从 Buffer 中读取数据:从 Buffer 中读取数据。 7. 关闭 Channel:关闭 Channel 对象。 8. 关闭 Selector:关闭 Selector 对象。 下面是一个简单的 NIO 例子: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class NIOClient { public static void main(String[] args) throws IOException { SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("localhost", 8888)); ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put("Hello, server!".getBytes()); buffer.flip(); socketChannel.write(buffer); buffer.clear(); int num = socketChannel.read(buffer); System.out.println("Received from server: " + new String(buffer.array(), 0, num)); socketChannel.close(); } } ``` 这个例子中,我们先创建了一个 SocketChannel 对象,并连接到指定的服务器。然后,我们创建了一个 ByteBuffer 对象,将需要写入的数据写入到 ByteBuffer 中,切换 ByteBuffer 的模式,从中读取数据并输出到控制台,最后关闭 SocketChannel 对象。 希望这份简单的介绍能够帮助你更好的了解 Java NIO API。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值