In fact, Java NiO introduces an asynchronous mechanism. asynchronous I/O has select poll epoll in Linux and supports multiplexing. In Java, it is implemented through a complete set of NiO classes, mainly including:
Bytebuffer
Socketchannel
Serversocketchannel
Selector
Selectionkey
Registration:
Channel calls register to register with selector,
Remove:
Selectionkey. Cancel // only remove the channel corresponding to the selectionkey from the selector. The socket is still active and needs to be disabled manually.
Channel. Close () // remove from selector, and close the socket object associated with the channel.
// Obtain a selector
Selector select = selector. open ();
Serversocketchannel Ss = serversocketchannel. open ();
// It must be set to non-blocking.
SS. configureblocking (false );
// Bind to an address
SS. socket (). BIND (New inetsocketaddress ("0.0.0.0", 5858 ));
// Register the channel with selector. A selectionkey is associated with the channel.
// When a connection comes in, select can return selectedkeys
SS. Register (select, selectionkey. op_accept );
While (select. Select ()> = 0 ){
// Return the ready keys.
Set <selectionkey> keyready = select. selectedkeys ();
// Poll the key in every ready state. The channel can be obtained through the key or deleted from the selector through the key.
For (iterator <selectionkey> iter = keyready. iterator (); ITER. hasnext ();){
Selectionkey Sk = ITER. Next ();
ITER. Remove ();
System. Out. println ("cancel" + select. Keys (). Size ());
Socketchannel client = NULL;
If (SK. Channel () instanceof serversocketchannel ){
Ss = (serversocketchannel) SK. Channel ();
Client = ss. Accept ();
System. Out. println ("accept:" + client. socket ());
// Client. socket (). Close ();
// It must be set to non-blocking.
Client. configureblocking (false );
// Register non-passive socket to Selector
Client. Register (select, selectionkey. op_read );
}
Else if (SK. Channel () instanceof socketchannel ){
Socketchannel CH = (socketchannel) SK. Channel ();
Bytebuffer recvbuf = bytebuffer. Allocate (100 );
// Bytebuffer in NIO must be used; otherwise, an error occurs.
Int Len = CH. Read (recvbuf );
If (LEN <0 ){
// You must disable the socket before removing it. Otherwise, many sockets are open.
Ch. socket (). Close ();
// Remove the channel from Selector
SK. Cancel ();
Continue;
}
Recvbuf. Flip ();
Ch. Write (recvbuf );
// SK. Cancel ();
System. Out. println ("cancel" + select. Keys (). Size () + "len" + Len );
Len = CH. Read (recvbuf );
// Disable the channel. At this time, the socket corresponding to the channel is closed and the channel is removed from the selector.
// Ch. Close ();
System. Out. println ("len" + Len );
}
Else {
System. Out. println ("error change ");
}
}
}
System. Out. println ("End ==== ");