一、回传协议接口和 UDP 方式实现 :
1. : :
import java.nio.channels.selectionkey; Importer java.io.ioException; Interface publique EchoprotoCol {void handleaccept (SELECTIONKEY KEY) lève ioException; VOID HandlereRead (SELECTIONKEKEY) lève IOException; Void HandleWrite (SELECTIONKEKEKEY) lève IOException; }2. 实现 :
Importer java.net.socketAddress; import java.nio.channels. *; import java.nio.bytebuffer; Importer java.io.ioException; Classe publique UDPECHOSELectorProtoCol implémente <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; // Taille maximale d'Echo Datagram Static Class ClientRecord {public socketAddress ClientAddress; Public ByteBuffer Buffer = ByteBuffer.Allocation (Echomax); } public void handleAccept (SELECTIONKEKEY KEY) lève ioException {} public void handleread (SelectionKey key) lève ioException {datagramchannel canal = (datagramchannel) key.channel (); ClientRecord ClNTRec = (clientRecord) key.Attachment (); clntec.buffer.clear (); // Préparez le tampon pour recevoir clntec.clientAddress = channel.receive (clntec.buffer); if (clntec.clientAddress! = null) {// Avons-nous reçu quelque chose? // enregistrez-vous avec le sélecteur Key.interestops (selectionKey.op_write); }} public void HandleWrite (SelectionKey Key) lève ioException {datagramChannel Channel = (datagramChannel) key.channel (); ClientRecord ClNTRec = (clientRecord) key.Attachment (); Clntec.Buffer.flip (); // Préparez le tampon pour l'envoi int bytessent = canal.send (clntec.buffer, clntec.clientAddress); if (bytessent! = 0) {// tampon complètement écrit? // ne vous intéresse plus à écrire key.interestops (selectionKey.op_read); }}}二、 Nio UDP 客户端:
Importer java.net.inetsocketAddress; import java.net.socketException; import java.nio.bytebuffer; import java.nio.channels.datagramchannel; classe publique UDPECHOCLIentNonBlocking {private static final int timeout = 3000; // Renvoyer le délai d'attente (millisecondes) Final statique privé int maxtries = 255; // maximum retransmissions public static void main (String args []) lève une exception {// convertir la chaîne d'entrée en octets en utilisant le charset par défaut [] byTesToSend = "0123456789AbcDefghijklmnOpQrStuvWxyz" .getBytes (); // Créer un canal et défini sur DatagramChannel non bloquant DatagramChannel = DatagramChannel.Open (); datagramchannel.configureblocking (false); DatagramChannel.Socket (). SetSoTimeout (Timeout); ByteBuffer WriteBuf = byteBuffer.Wrap (byTestoSend); ByteBuffer readBuf = byteBuffer.Allocation (MaxTries); datagramChannel = datagramchannel.connect (new IneTsocketAddress ("127.0.0.1", 5500)); int totalBytesrcvd = 0; // Total des octets reçus jusqu'à présent int bytesrcvd; // octets reçus dans la dernière lecture while (totalBytesrcvd <byTestoSend.length) {if (writeBuf.hasreMaining ()) {datagramchannel.write (writeBuf); } if ((bytesrcvd = datagramChannel.read (readBuf)) == -1) {Throw New socketException ("Connection fermé prématurément"); } totalBytesrcvd + = bytesrcvd; System.out.print ("."); // faire autre chose} System.out.println ("Reçu:" + Nouvelle chaîne (readBuf.Array (), 0, TotalBytesrcvd)); datagramchannel.close (); }}三、 Nio UDP 服务端:
Importer java.io.ioException; Importer java.net.inetsocketAddress; import java.nio.channels. *; Importer java.util.iterator; classe publique UDPECHOSERVERSELECLECT {private static final int timeout = 3000; // WAIT TIMEout (millisecondes) public static void main (String [] args) lève ioException {// Créer un sélecteur pour multiplexer les connexions client. Sélecteur sélecteur = sélecteur.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) {// Exécutez pour toujours, recevoir et faire écho aux datagrammes // attendez la tâche ou jusqu'à l'expiration du délai d'expiration if (selector.select (timeout) == 0) {System.out.print ("."); continuer; } // Obtenez Iterator sur le jeu de touches avec des E / S pour traiter Iterator <lelectionKey> keyiter = Selector.SelectedKeys (). Iterator (); while (keyiter.hasnext ()) {SelectionKey key = keyiter.next (); // La touche est un masque de bits // canal de socket client a des données en attente? if (key.isreadable ()) echoselectorprotocol.handleread (key); // Le canal de socket client est disponible pour l'écriture et // la clé est valide (c'est-à-dire le canal non fermé). if (key.isvalid () && key.iswitable ()) echoselectorprotocol.handlewrite (key); keyiter.remove (); }}}}°