一、回传协议接口和 tcp 方式实现 :
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.nio.channels.*; import java.nio.bytebuffer; import java.io.ioException; clase pública tcpechoselectorprotocol implementa ecoprotocol {private int bufsize; // Tamaño del búfer de E/S public EchoselectorProtocol (int bufsize) {this.bufSize = bufSize; } public void HandleAccept (selectionKey key) lanza ioexception {Socketchannel clntchan = ((ServersocketchEnchannel) Key.channel ()). Acept (); clntchan.configureBlocking (falso); // debe estar sin bloquear para registrar // registrar el selector con el nuevo canal para leer y adjuntar byte buffer clntchan.register (key.selector (), selectionKey.op_read, bytebuffer.allocate (bufsize)); } public void Handleread (Key KeyKey) lanza IOException {// El canal de socket de cliente tiene datos pendientes de socketchannel clntchan = (Socketchannel) key.channel (); Bytebuffer buf = (bytebuffer) key.attachment (); long bytesread = clntchan.read (buf); if (bytesread == -1) {// ¿Cerró el otro? clntchan.close (); } else if (bytesread> 0) {// indica a través de la tecla que la lectura/escritura son de interés ahora. key.interestops (selectionKey.op_read | selectionKey.op_write); }} public void HandleWrite (selectionKey Key) lanza el canal IOException { / * * está disponible para escribir, y la clave es válida (es decir, canal de cliente * no cerrado). */ // Recuperar datos lee anteriormente bytebuffer buf = (bytebuffer) key.attachment (); buf.flip (); // Prepare el amortiguador para escribir Socketchannel Clntchan = (Socketchannel) Key.channel (); clntchan.write (buf); if (! buf.hasremaining ()) {// buffer completamente escrito? // No queda nada, así que ya no está interesado en Write Key.interestops (selectionKey.op_read); } buf.compact (); // dejar espacio para que se lean más datos en}}二、 NIO TCP 客户端 :
import java.net.InetSocketAddress; import java.net.socketException; import java.nio.bytebuffer; import java.nio.channels.socketchannel; clase pública TCPeCHOCLientNonBlocking {public static void main (string args []) lanza la excepción {String Server = "127.0.0.1"; // Nombre del servidor o dirección IP // Convertir la cadena de entrada a bytes utilizando el byte de charset predeterminado [] argumento = "0123456789ABCDefghijklmnopqrstuvwxyz" .getBytes (); int servport = 5500; // Crear canal y establecer en Socketchannel no bloqueado clntchan = Socketchannel.open (); clntchan.configureBlocking (falso); // Iniciar la conexión al servidor y sondear repetidamente hasta que complete if (! Clntchan.connect (new inetSocketAddress (servidor, servport))) {while (! Clntchan.finishconnect ()) {system.out.print ("."); // haz algo más}} bytebuffer writeBuf = byteBuffer.wrap (argumento); Bytebuffer readBuf = bytebuffer.allocate (argumento.length); int totalBytesrcvd = 0; // bytes totales recibidos hasta ahora int bytesrcvd; // bytes recibidos en la última lectura while (totalbytesrcvd <argument.length) {if (writeBuf.hasrErainSering ()) {clntchan.write (writeBuf); } if ((bytesrcvd = clntchan.read (readBuf)) == -1) {tire nueva SocketException ("Conexión cerrada prematuramente"); } TotalBytesrcvd += bytesrcvd; System.out.print ("."); // hacer algo más} system.out.println ("Recibido:" +// Convertir a cadena por cadena de charset predeterminada nueva cadena (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; clase pública TCPSerVerselector {private estático final int bufsize = 256; // Tamaño del búfer (bytes) Private estático final int Tiempout = 3000; // tiempo de espera (milisegundos) public static void main (string [] args) lanza ioexception {int [] puertos = {5500}; // Crear un selector para multiplex Sockets y conexiones selector selector = selector.open (); // Crear canal de socket de escucha para cada puerto y registrar selector para (int Port: Ports) {ServerSocketchannel listnchannel = Serversocketchannel.open (); listnchannel.socket (). bind (nuevo inetSocketAddress (puerto)); listnchannel.configureBlocking (falso); // debe estar sin bloquear para registrar // registrar selector con el canal. La clave devuelta se ignora listnchannel.register (selector, selectionKey.op_accept); } // Cree un controlador que implementará el protocolo TCPProtocol Protocol = new TCPeChoselectorProtocol (BUFSize); mientras (true) {// ejecuta para siempre, procesamiento de operaciones de E/S disponibles // Espere a que algún canal esté listo (o tiempo de espera) if (selector.select (timeout) == 0) {// Devuelve # de chans listos 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 servidor tiene solicitudes de conexión pendientes? if (key.isaceptable ()) {System.out.println ("----- Aceptar -----"); protocol.handleAccept (clave); } // El canal de socket de cliente tiene datos pendientes? if (key.iseadable ()) {System.out.println ("---- Read -----"); protocol.handleread (clave); } // El canal de socket del cliente está disponible para escribir y // La clave es válida (es decir, canal no cerrado)? if (key.isValid () && key.iswritable ()) {System.out.println ("---- write -----"); protocol.handlewrite (clave); } keyiter.remove (); // Eliminar del conjunto de teclas seleccionadas}}}}以上就是本文的全部内容 , 查看更多 java 的语法 , 大家可以关注 : 《pensando en java 中文手册》、《 jdk 1.7 参考手册官方英文版》、《 jdk 1.6 api java 中文参考手册》、《 jdk 1.5 api java 中文参考手册》 也希望大家多多支持武林网。 也希望大家多多支持武林网。