NiO usage method 2

xiaoxiao2021-03-06  41

The previous possibility is still inconvenient, then the specific one: package zzzhc;

/ ** * @author zzzhc * * / public interface SocketHandler extends ConnectHandler, ReadWriteHandler {void onConnected (); void onConnectFailed (String msg); / * * * After the data is read from the CHANNEL. * * / Void onRead (); / ** * After the number you want to write, the ChannNel is written after CHANNNEL. * * / Void OnWrite (); void onclosed String MSG);

} // Abstract implementation package zzzhc;

import java.io.IOException; import java.net.SocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel;

/ ** * @author zzzhc * * / public abstract class AbstractSocketHandler implements SocketHandler {public final static int DEFAULT_BUFFER_SIZE = 2 * 1024;

Protected factory selectorprocessor processor;

Protected final socketchannel sc;

Protected final bytebuffer readbuf;

Protected final bytebuffer writebuf; protected socketaddress localaddress;

Protected socketaddress remoteaddress;

Protected Boolean Connected = False;

Protected Boolean Closed = False;

public AbstractSocketHandler (SelectorProcessor processor, SocketAddress remoteAddress) throws IOException {this.processor = processor; this.remoteAddress = remoteAddress; this.sc = SocketChannel.open (); this.sc.configureBlocking (false); this.sc.connect (remoteAddress ); int readSize = DEFAULT_BUFFER_SIZE; int writeSize = DEFAULT_BUFFER_SIZE; try {readSize = sc.socket () getReceiveBufferSize ();. writeSize = sc.socket () getSendBufferSize ();.} catch (SocketException e1) {} readBuf = ByteBuffer. allocate (readSize); writeBuf = ByteBuffer.allocate (writeSize); processor.register (sc, this, SelectionKey.OP_CONNECT);} public AbstractSocketHandler (SelectorProcessor processor, SocketAddress remoteAddress, ByteBuffer readBuf, ByteBuffer writeBuf) throws IOException {this.processor = Processor; this.Remoteaddress = Remoteaddress; THI S.SC = Socketchannel.Open (); this.sc.configureblocking (false); this.sc.connect (remoteaddress); readbuf.clear (); writebuf.clear (); this.readbuf = readbuf; excitebuf = Writebuf; Processor.register (sc, this, selectionKey.op_connect);

public AbstractSocketHandler (SelectorProcessor processor, SocketChannel sc) {this.processor = processor; this.sc = sc; this.connected = true; if (this.sc.isBlocking ()) {try {this.sc.configureBlocking (false); } catch (IOException e) {e.printStackTrace ();}} int readSize = DEFAULT_BUFFER_SIZE; int writeSize = DEFAULT_BUFFER_SIZE; try {readSize = sc.socket () getReceiveBufferSize ();.. writeSize = sc.socket () getSendBufferSize () ;} catch (SocketException e1) {} readBuf = ByteBuffer.allocateDirect (readSize); writeBuf = ByteBuffer.allocateDirect (writeSize); processor.register (sc, this, SelectionKey.OP_READ);} public AbstractSocketHandler (SelectorProcessor processor, SocketChannel sc, Bytebuffer Readbuf, Bytebuffer Writebuf) {this.processor = processor; this.sc = sc; this.connecte D = true; if (this.sc.isblocking ()) {Try {this.sc.configureblocking (false);} catch (ooException e) {E.PrintStackTrace ();}}}}}}}}}}}}}}}}}}}}}}}} (); This.readbuf = readbuf; this.writebuf = writebuf; processor.register (sc, this, selectionKey.op_read);}

Public void onConnected () {system.out.println ("Connect to" this.getRemoteAddress () "OK");

Public void OnConnectFailed (String MSG) {System.out.println ("Connect To" this.getRemoteAddress () "Failed:" MSG);

/ ** * If you are not finished at a time, you must call readbuf.compact (). * If you have finished reading, you must call readbuf.clear (). * / Public void onRead () {readbuf.flip (); int LEN = Readbuf.limit (); byte [] buf = new byte [len]; readbuf.get (buf); readbuf.clear (); system.out.print (new string (buf)); WriteBuf.Put (BUF); Writebuf.flip (); enableWrite (); public void onwrite () {}

Public void onclosed (string msg) {system.out.println ("Channel Closed: MSG);

public void handleConnect () {try {if (sc.finishConnect ()) {onConnected (); connected = true;} else {onConnectFailed ( "");} processor.addInterestOps (sc, SelectionKey.OP_READ);} catch (IOException e) {E.PrintStackTrace (); onConnectFailed (E.getMessage ());}}

Public void handleread () {Try {//system.out.println ("lonread"); int Len = sc.read (readbuf); if (len == -1) {// Closed Dispose ("Channel Been Closed Correct) ");} Else {//readbuf.flip (); onRead (); processor.addinterestOps (sc, selectionkey.op_read);}} catch (ooException e) {E.PrintStackTrace (); Dispose (E.GetMessage () }}

Public void handlewrite () {if (write () == true) {onWrite ();}} / ** * Write the data in WriteBuf into the SocketChannel, if you write the clear WriteBuf to return true, otherwise return false. * The flip () method should be called before using this method. * @Return * / protected boolean Write () {if (WriteBuf.hasRemaining ()) {Try {sc.write (WriteBuf);} catch (ooexception e) {E.PrintStackTrace (); dispose (E.GetMessage ()); Return False;}}}}}}} {enableWrite (); return false;} else {WriteBuf.clear (); return true;} PUBLIC SOCKETDRESS GETLOCALADDRESS () {if (localaddress == null) {localaddress = this.sc.socket (). getLocalsocketAddress ();} return localaddress;}

Public socketaddress getRemoteAddress () {if (remoteaddress == null) {remoteaddress = this.sc.socket (). getRemotesocketAddress ();} return remoteaddress;}

Public void dispose (String MSG) {if (! closed) {close; processor.closechannel (sc); onclosed (msg);}}

Public boolean isconnected () {returnid;

Public boolean isclosed () {return closed;} public void close () {processor.closechannel (sc);

Public void enableRead () {processor.addinterest »}

Public void enableWrite () {processor.addinterest »;}

} // How to use, first run NC-L -P 1234 in Console to run echoclientPackage zzzhc;

Import java.io.ioException; import java.net.inetsocketaddress; import java.net.socketaddress; / ** * @Author zzzhc * * / public Class Echoclient Extends AbstractSocketHandler {Public Echoclient (SelectorProcessor Processor, SocketAddress Remote). ooException {super

public static void main (String [] args) throws IOException {EchoClient client = new EchoClient (SelectorProcessor.getDefaultInstance (), new InetSocketAddress ( "localhost", 1234));}} // complex package zzzhc point;

import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URL; import java.nio.channels.FileChannel ;

/ ** * @Author zzzhc * / public class SimplehttpClient Extends AbstractSocketHandler {

Public final static int start_connect = 0;

Public final static int connect_ok = 1;

Public final static int connect_failed = 2;

Public final static int try_send_request = 10;

Public final static int request_sent = 11;

// public final static int RECV_RESPONSE_HEADER = 20; public final static int response_header_end = 21;

Public final static int start_data_transfer = 30;

Public final static int end_data_transfer = 31;

Protected int stat; start_connect;

Protected URL URL;

PROTECTED FileChannel FC;

Protected FileOutputStream Out; Private StringBuffer Header = new stringbuffer ();

public SimpleHttpClient (SelectorProcessor processor, SocketAddress remote, URL url) throws IOException {super (processor, remote); this.url = url;} public void onConnected () {super.onConnected (); try {Thread.sleep (10); } Catch (Exception E) {} status = connection_ok; fillheader (URL); enableWrite (); status = try_send_request;}

Protected Void FillHeader (URL URL) {WriteBuf.clear (); WriteBuf.Put ("get" .getbytes ()). Put (Url.getPath (). getBytes ()). PUT ("http / 1.1" .GetBytes ))). PUT ((byte) '/r' ).put(te' / n '); WriteBuf.Put ("Host:" .GetBytes ()). Put (url.getHost (). getBytes () ) .put (Byte) '/ r') .put ((byte) '/ n'); WriteBuf.put ((byte) '/r' ).put(((( ((Byte)' / n '); WriteBuf. FLIP ();

Public void onConnectFailed (String MSG) {Super.onnectFailed (MSG); status = connect_failed; system.exit (0);

Public void onread () {readbuf.flip (); switch (status) {copy request_sent: int pos = readbuf.limit (); byte b; rest (readbuf.hasremaining ()) {b = readbuf.get (); if (b == '/ r') {IF (POS - Readbuf.Position ()> = 3) {b = readbuf.get (); // n b = readbuf.get (); if (b == ' / r ') {b = readbuf.get (); /// n readbuf.compact (); status = response_header_end; return;}}}}}}}}}}}}}}}}}}} Break; Case Response_Header_end: status = start_data_transfer; Case Start_data_Transfer: System.out.println ("Start Data Transfer."); If (out == NULL) {String file = url.getfile (). Trim (); if ("" .Equals (file) {file = "index.html";} int idx = file.lastIndexof ('/'); if (IDX! = -1) {file = file.substring (IDX 1);} if ("" .Equals (file)) {file = "index.html";} try {system.out.println ("open" file "to write."); out = new fileoutputstream (file); fc =

Out.getChannel ();} catch (filenotfoundexception e) {// this stay NOT HAPPEND. E.PrintStackTrace (); close ();}} try {whene ();} () {fc.write }}}} Catch (ioException e) {E.PrintStackTrace (); close ();} readbuf.clear (); break; default: system.out.println ("status:" status);}} public void onclosed (String) Msg) {super.onclosed (msg); try {if (out! = null) {out.close (); fc.close ();}} catch (ooException e) {E.PrintStackTrace ();} system.exit (0);

Public void onwrite () {status = request_sent; system.out.println ("Request Sent.");}

new SimpleHttpClient (SelectorProcessor.getDefaultInstance (), new InetSocketAddress ( "www.sohu; public static void main (String [] args) throws IOException {URL url = new (" http://www.sohu.com/ ") URL. COM ", 80), URL);}}

转载请注明原文地址:https://www.9cbs.com/read-82653.html

New Post(0)