Java Socket编程实例(五)- NIO UDP实践

所属分类: 软件编程 / java 阅读数: 62
收藏 0 赞 0 分享

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

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.net.SocketAddress; 
import java.nio.channels.*; 
import java.nio.ByteBuffer; 
import java.io.IOException; 
 
public class UDPEchoSelectorProtocol implements <span style="font-size: 1em; line-height: 1.5;">EchoProtocol </span><span style="font-size: 1em; line-height: 1.5;">{</span> 
  private static final int ECHOMAX = 255; // Maximum size of echo datagram 
 
  static class ClientRecord { 
    public SocketAddress clientAddress; 
    public ByteBuffer buffer = ByteBuffer.allocate(ECHOMAX); 
  } 
 
  public void handleAccept(SelectionKey key) throws IOException { 
     
  } 
 
  public void handleRead(SelectionKey key) throws IOException { 
    DatagramChannel channel = (DatagramChannel) key.channel(); 
    ClientRecord clntRec = (ClientRecord) key.attachment(); 
    clntRec.buffer.clear(); // Prepare buffer for receiving 
    clntRec.clientAddress = channel.receive(clntRec.buffer); 
    if (clntRec.clientAddress != null) { // Did we receive something? 
      // Register write with the selector 
      key.interestOps(SelectionKey.OP_WRITE); 
    } 
  } 
 
  public void handleWrite(SelectionKey key) throws IOException { 
    DatagramChannel channel = (DatagramChannel) key.channel(); 
    ClientRecord clntRec = (ClientRecord) key.attachment(); 
    clntRec.buffer.flip(); // Prepare buffer for sending 
    int bytesSent = channel.send(clntRec.buffer, clntRec.clientAddress); 
    if (bytesSent != 0) { // Buffer completely written? 
      // No longer interested in writes 
      key.interestOps(SelectionKey.OP_READ); 
    } 
  } 
 
}

二、NIO UDP客户端:

import java.net.InetSocketAddress; 
import java.net.SocketException; 
import java.nio.ByteBuffer; 
import java.nio.channels.DatagramChannel; 
 
public class UDPEchoClientNonblocking { 
 
  private static final int TIMEOUT = 3000; // Resend timeout (milliseconds) 
  private static final int MAXTRIES = 255; // Maximum retransmissions 
   
  public static void main(String args[]) throws Exception { 
    // Convert input String to bytes using the default charset 
    byte[] bytesToSend = "0123456789abcdefghijklmnopqrstuvwxyz".getBytes(); 
 
    // Create channel and set to nonblocking 
    DatagramChannel datagramChannel = DatagramChannel.open(); 
    datagramChannel.configureBlocking(false); 
    datagramChannel.socket().setSoTimeout(TIMEOUT); 
     
    ByteBuffer writeBuf = ByteBuffer.wrap(bytesToSend); 
    ByteBuffer readBuf = ByteBuffer.allocate(MAXTRIES); 
     
    datagramChannel = datagramChannel.connect(new InetSocketAddress("127.0.0.1", 5500)); 
 
    int totalBytesRcvd = 0; // Total bytes received so far 
    int bytesRcvd; // Bytes received in last read 
    while (totalBytesRcvd < bytesToSend.length) { 
      if (writeBuf.hasRemaining()) { 
        datagramChannel.write(writeBuf); 
      } 
      if ((bytesRcvd = datagramChannel.read(readBuf)) == -1) { 
        throw new SocketException("Connection closed prematurely"); 
      } 
      totalBytesRcvd += bytesRcvd; 
      System.out.print("."); // Do something else 
    } 
 
    System.out.println("Received: " + new String(readBuf.array(), 0, totalBytesRcvd)); 
    datagramChannel.close(); 
  } 
}

三、NIO UDP服务端:

import java.io.IOException; 
import java.net.InetSocketAddress; 
import java.nio.channels.*; 
import java.util.Iterator; 
 
public class UDPEchoServerSelector { 
 
  private static final int TIMEOUT = 3000; // Wait timeout (milliseconds) 
 
  public static void main(String[] args) throws IOException { 
    // Create a selector to multiplex client connections. 
    Selector selector = Selector.open(); 
 
    DatagramChannel channel = DatagramChannel.open(); 
    channel.configureBlocking(false); 
    channel.socket().bind(new InetSocketAddress(5500)); 
    channel.register(selector, SelectionKey.OP_READ, new UDPEchoSelectorProtocol.ClientRecord()); 
 
    UDPEchoSelectorProtocol echoSelectorProtocol = new UDPEchoSelectorProtocol(); 
    while (true) { // Run forever, receiving and echoing datagrams 
      // Wait for task or until timeout expires 
      if (selector.select(TIMEOUT) == 0) { 
        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 
 
        // Client socket channel has pending data? 
        if (key.isReadable()) 
          echoSelectorProtocol.handleRead(key); 
 
        // Client socket channel is available for writing and 
        // key is valid (i.e., channel not closed). 
        if (key.isValid() && key.isWritable()) 
          echoSelectorProtocol.handleWrite(key); 
 
        keyIter.remove(); 
      } 
    } 
  } 
 
}

以上就是本文的全部内容,查看更多Java的语法,大家可以关注:《Thinking in Java 中文手册》、《JDK 1.7 参考手册官方英文版》、《JDK 1.6 API java 中文参考手册》、《JDK 1.5 API java 中文参考手册》,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Java基于反射机制实现全部注解获取的方法示例

这篇文章主要介绍了Java基于反射机制实现全部注解获取的方法,结合实例形式分析了java反射机制获取注解的具体实现方法与操作注意事项,需要的朋友可以参考下
收藏 0 赞 0 分享

Java 信号量Semaphore的实现

这篇文章主要介绍了Java 信号量Semaphore的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

eclipse+maven+spring mvc项目基本搭建过程

这篇文章主要介绍了eclipse+maven+spring mvc项目基本搭建过程,本文图文并茂给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Spring boot集成swagger2生成接口文档的全过程

这篇文章主要给大家介绍了关于Spring boot集成swagger2生成接口文档的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Spring boot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
收藏 0 赞 0 分享

Java冒泡排序法和选择排序法的实现

这篇文章主要介绍了Java冒泡排序法和选择排序法的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Spring Cloud Alibaba教程之Sentinel的使用

这篇文章主要介绍了Spring Cloud Alibaba教程之Sentinel的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Josephus环的四种解法(约瑟夫环)基于java详解

这篇文章主要介绍了Josephus环的四种解法(约瑟夫环)基于java详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Java继承Thread类创建线程类示例

这篇文章主要介绍了Java继承Thread类创建线程类,结合实例形式分析了java线程操作相关使用技巧与注意事项,需要的朋友可以参考下
收藏 0 赞 0 分享

Java使用Callable和Future创建线程操作示例

这篇文章主要介绍了Java使用Callable和Future创建线程操作,结合实例形式分析了java使用Callable接口和Future类创建线程的相关操作技巧与注意事项,需要的朋友可以参考下
收藏 0 赞 0 分享

springBoot使用JdbcTemplate代码实例

这篇文章主要介绍了springBoot使用JdbcTemplate代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多