Java Socket编程实例(四)- NIO TCP实践

作者:kingxss 时间:2021-10-07 13:44:35 

一、回传协议接口和TCP方式实现:

1.接口:


import java.nio.channels.SelectionKey;
import java.io.IOException;

public interface EchoProtocol {
void handleAccept(SelectionKey key) throws IOException;
void handleRead(SelectionKey key) throws IOException;
void handleWrite(SelectionKey key) throws IOException;
}

2.实现:


import java.nio.channels.*;
import java.nio.ByteBuffer;
import java.io.IOException;

public class TCPEchoSelectorProtocol implements EchoProtocol{
 private int bufSize; // Size of I/O buffer

public EchoSelectorProtocol(int bufSize) {
   this.bufSize = bufSize;
 }

public void handleAccept(SelectionKey key) throws IOException {
   SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
   clntChan.configureBlocking(false); // Must be nonblocking to register
   // Register the selector with new channel for read and attach byte buffer
   clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufSize));

}

public void handleRead(SelectionKey key) throws IOException {
   // Client socket channel has pending data
   SocketChannel clntChan = (SocketChannel) key.channel();
   ByteBuffer buf = (ByteBuffer) key.attachment();
   long bytesRead = clntChan.read(buf);
   if (bytesRead == -1) { // Did the other end close?
     clntChan.close();
   } else if (bytesRead > 0) {
     // Indicate via key that reading/writing are both of interest now.
     key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
   }
 }

public void handleWrite(SelectionKey key) throws IOException {
   /*
    * Channel is available for writing, and key is valid (i.e., client channel
    * not closed).
    */
   // Retrieve data read earlier
   ByteBuffer buf = (ByteBuffer) key.attachment();
   buf.flip(); // Prepare buffer for writing
   SocketChannel clntChan = (SocketChannel) key.channel();
   clntChan.write(buf);
   if (!buf.hasRemaining()) { // Buffer completely written?  
     //Nothing left, so no longer interested in writes
     key.interestOps(SelectionKey.OP_READ);
   }
   buf.compact(); // Make room for more data to be read in
 }

}

二、NIO TCP客户端:


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 {
   String server = "127.0.0.1"; // Server name or IP address
   // Convert input String to bytes using the default charset
   byte[] argument = "0123456789abcdefghijklmnopqrstuvwxyz".getBytes();

int servPort = 5500;

// Create channel and set to nonblocking
   SocketChannel clntChan = SocketChannel.open();
   clntChan.configureBlocking(false);

// Initiate connection to server and repeatedly poll until complete
   if (!clntChan.connect(new InetSocketAddress(server, servPort))) {
     while (!clntChan.finishConnect()) {
       System.out.print("."); // Do something else
     }
   }
   ByteBuffer writeBuf = ByteBuffer.wrap(argument);
   ByteBuffer readBuf = ByteBuffer.allocate(argument.length);
   int totalBytesRcvd = 0; // Total bytes received so far
   int bytesRcvd; // Bytes received in last read
   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("."); // Do something else
   }

System.out.println("Received: " + // convert to String per default charset
       new String(readBuf.array(), 0, totalBytesRcvd).length());
   clntChan.close();
 }
}

三、NIO TCP服务端:


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.Iterator;

public class TCPServerSelector {
 private static final int BUFSIZE = 256; // Buffer size (bytes)
 private static final int TIMEOUT = 3000; // Wait timeout (milliseconds)

public static void main(String[] args) throws IOException {
   int[] ports = {5500};
   // Create a selector to multiplex listening sockets and connections
   Selector selector = Selector.open();

// Create listening socket channel for each port and register selector
   for (int port : ports) {
     ServerSocketChannel listnChannel = ServerSocketChannel.open();
     listnChannel.socket().bind(new InetSocketAddress(port));
     listnChannel.configureBlocking(false); // must be nonblocking to register
     // Register selector with channel. The returned key is ignored
     listnChannel.register(selector, SelectionKey.OP_ACCEPT);
   }

// Create a handler that will implement the protocol
   TCPProtocol protocol = new TCPEchoSelectorProtocol(BUFSIZE);

while (true) { // Run forever, processing available I/O operations
     // Wait for some channel to be ready (or timeout)
     if (selector.select(TIMEOUT) == 0) { // returns # of ready chans
       System.out.print(".");
       continue;
     }

// Get iterator on set of keys with I/O to process
     Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
     while (keyIter.hasNext()) {
       SelectionKey key = keyIter.next(); // Key is bit mask
       // Server socket channel has pending connection requests?
       if (key.isAcceptable()) {
         System.out.println("----accept-----");
         protocol.handleAccept(key);
       }
       // Client socket channel has pending data?
       if (key.isReadable()) {
         System.out.println("----read-----");
         protocol.handleRead(key);
       }
       // Client socket channel is available for writing and  
       // key is valid (i.e., channel not closed)?
       if (key.isValid() && key.isWritable()) {
         System.out.println("----write-----");
         protocol.handleWrite(key);
       }
       keyIter.remove(); // remove from set of selected keys
     }
   }
 }

}

标签:Java,Socket,NIO,TCP
0
投稿

猜你喜欢

  • 史上最全图文讲解Java泛型

    2022-08-23 20:27:47
  • spring boot 注入 property的三种方式(推荐)

    2023-01-23 05:10:27
  • Java数据结构之优先级队列(堆)图文详解

    2021-06-25 13:47:58
  • springboot项目启动慢的问题排查方式

    2023-06-19 18:58:40
  • Java中Lambda表达式的进化之路详解

    2023-04-19 21:17:42
  • android使用PullToRefresh实现下拉刷新和上拉加载

    2023-08-06 11:06:58
  • intellij idea使用git stash暂存一次提交的操作

    2023-03-08 08:30:11
  • Java RateLimiter的限流详解

    2023-01-06 17:14:12
  • Java面试题及答案集锦(基础题122道,代码题19道)

    2023-11-25 12:36:17
  • spring boot实现过滤器和拦截器demo

    2023-08-24 07:15:01
  • 浅析Java中的异常处理机制

    2021-08-19 05:42:48
  • PageHelper插件实现一对多查询时的分页问题

    2021-11-05 07:02:34
  • Java中ResultSetMetaData 元数据的具体使用

    2021-06-25 12:38:13
  • 常用Maven库,镜像库及maven/gradle配置(小结)

    2023-11-20 23:44:00
  • Java 遍历取出Map集合key-value数据的4种方法

    2022-02-03 02:48:59
  • SpringBoot2.1.4中的错误处理机制

    2023-11-06 02:48:47
  • IDEA创建Java项目文件并运行教程解析

    2023-01-14 15:50:47
  • Jersey Restful接口如何获取参数的问题

    2023-10-29 14:44:16
  • Spring实例化bean的方式代码详解

    2022-04-04 08:46:09
  • Java上传视频实例代码

    2023-06-24 04:17:45
  • asp之家 软件编程 m.aspxhome.com