一、回传协议接口和 UDP 方式实现 :
1. 接口 :
import java.nio.channels.selectionKey; import java.io.ioException; Public Interface Echoprotocol {Void HandleAccept (SelectionKey Key) lanza IOException; Void Handleread (Key KeyKey) lanza IOException; Void HandleWrite (SelectionKey Key) lanza IOException; }2. 实现.
import java.net.socketaddress; import java.nio.channels.*; import java.nio.bytebuffer; import java.io.ioException; clase pública UDPechoselectorProtocol implementos <span style = "font-size: 1em; line-height: 1.5;"> ecoprotocol </span> <span style = "font-size: 1Em; line-height: 1.5;"> {</span> inteco final estático privado = 255; // Tamaño máximo de la clase estática de datagrama de echo ClientRecord {public SocketAddress ClientAddress; public bytebuffer buffer = bytebuffer.allocate (Echomax); } public void HandleAccept (Key Key Key Key) lanza IOException {} public void Handleread (Key Key Key) lanza IOException {DataGramChannel Channel = (DataGramChannel) key.channel (); ClientRecord clntrec = (clientRecord) key.attachment (); clntrec.buffer.clear (); // Prepare el búfer para recibir clntrec.clientaddress = channel.Receive (clntrec.buffer); if (clntrec.clientaddress! = null) {// ¿Recibimos algo? // Registre la escritura con el selector Key.interestops (selectionKey.op_write); }} public void handleWrite (selectionKey key) lanza ioexception {datagramChannel canal = (dataGramChannel) key.channel (); ClientRecord clntrec = (clientRecord) key.attachment (); clntrec.buffer.flip (); // Preparar búfer para enviar int bytessent = channel.send (clntrec.buffer, clntrec.clientaddress); if (bytessent! = 0) {// buffer completamente escrito? // ya no está interesado en Write Key.interestops (selectionKey.op_read); }}}二、 Nio UDP 客户端 :
import java.net.InetSocketAddress; import java.net.socketException; import java.nio.bytebuffer; import java.nio.channels.datagramchannel; clase pública UDPeChoclientnonBlocking {private static final int timeOut = 3000; // Resen Tiempo de espera (milisegundos) Private estático final int maxtries = 255; // Máximo retransmisiones pública void estatic void (string args []) lanza la excepción {// Convertir la cadena de entrada a bytes utilizando el byte de charset predeterminado [] byTestosend = "0123456789abcdefghijklmnopqrstuvwxyz" .getBytes ();; // Crear canal y establecer en DataGramChannel DataGramChannel = DataGramChannel.open (); dataGramChannel.ConfigureBlocking (falso); dataGramchannel.socket (). setSotimeOut (Tiempo de espera); Bytebuffer writeBuf = bytebuffer.wrap (byTestosend); Bytebuffer readBuf = bytebuffer.allocate (maxtries); dataGramchannel = dataGramchannel.connect (nuevo inetSocketAddress ("127.0.0.1", 5500)); int totalBytesrcvd = 0; // bytes totales recibidos hasta ahora int bytesrcvd; // bytes recibidos en la última lectura while (totalbytesrcvd <bytestosend.length) {if (writeBuf.hasremaning ()) {dataGramchannel.write (writeBuf); } if ((bytesrcvd = dataGramChannel.read (readBuf)) == -1) {Throw New SocketException ("Conexión cerrada prematuramente"); } TotalBytesrcvd += bytesrcvd; System.out.print ("."); // hacer algo más} system.out.println ("Recibido:" + nueva cadena (readBuf.Array (), 0, TotalBytesrcvd)); dataGramchannel.close (); }}三、 Nio UDP 服务端 :
import java.io.ioException; import java.net.InetSocketAddress; import java.nio.channels.*; import java.util.iterator; clase pública UDPeCHOSERVERSElector {private static final int timeOut = 3000; // Tiempo de espera de espera (MilliseConds) public static void main (string [] args) lanza ioexception {// crea un selector a las conexiones de cliente multiplex. Selector selector = selector.open (); Channel de dataGramchannel = dataGramchannel.open (); Channel.ConfigureBlocking (falso); Channel.socket (). Bind (nuevo inetSocketAddress (5500)); Channel.register (selector, selectionKey.op_read, nuevo UDPechoselectorProtocol.clientRecord ()); UDPechoselectorProtocol EchoSelectorProtocol = new UDPeChoselectorProtocol (); while (true) {// ejecutar para siempre, recibir y hacer eco de los datagramas // espere la tarea o hasta que el tiempo de espera expire si (selector.select (timeout) == 0) {system.out.print ("."); continuar; } // Obtener iterador en el conjunto de claves con E/S para procesar iterador <selectionKey> keyiter = selector.selectedKeys (). Iterator (); while (keyiter.hasnext ()) {selectionKey key = keyiter.next (); // La tecla es la máscara de bits // el canal de socket del cliente tiene datos pendientes? if (key.iseadable ()) EchoSelectorProtocol.Handleread (Key); // El canal de socket del cliente está disponible para escribir y // La tecla es válida (es decir, canal no cerrado). if (key.isValid () && key.iswritable ()) echoselectorProtocol.handlewrite (Key); keyiter.remove (); }}}}以上就是本文的全部内容 , 查看更多 java 的语法 , 大家可以关注 : 《pensando en java 中文手册》、《 jdk 1.7 参考手册官方英文版》、《 jdk 1.6 api java 中文参考手册》、《 jdk 1.5 api java 中文参考手册》 也希望大家多多支持武林网。 也希望大家多多支持武林网。