Click to enter _ more _java thousand ask
1, how to write non-blocking Socketchannel program
Find out what the socket looks for here: what the socket is
Learn Socketchannel See here: What is the difference between sockets and Socketchannel
The biggest benefit of using Socketchannel is the ability to do non-blocking IO, which is returned directly after each link, without blocking the thread. Tasks that require multiple threads can be done with a few threads, reducing performance consumption.
Understanding blocking, non-blocking see here: What is the difference between blocking and non-blocking?
To write Socketchannel, you need to understand the following classes in the Java.nio package:
1. Serversocketchannel
An alternative class of serversocket that supports blocking and non-blocking communication.
Socketchannel
An alternative class of sockets that supports blocking and non-blocking communication.
Selector
Receive Client Connection readiness events for Serversocketchannel monitoring and connect server read-ready and write-ready events for socketchannel monitoring.
Selectionkey
Represents the handle to the Selector register event for Serversocketchannel and Socketchannel. When a Selectionkey object is in the Selected-keys collection of a Selector object, it indicates that the event associated with the Selectionkey object has occurred.
Our two-part code is introduced through the client and the service side.
Service-Side code:
Public classSocketchannelserver {Private intPort =8000;//Port Public Socketchannelserver() throws Exception {Selector Selector = Selector.open (); Serversocketchannel Serverchannel = Serversocketchannel.open (); Serverchannel.configureblocking (false);//Set to non-blocking mode, if true then the traditional blocking modeServerchannel.socket (). Bind (NewInetsocketaddress (port));//Bind IP and PortServerchannel.register (selector, selectionkey.op_accept);//Registration while(true) {System. out. println ("Waiting accept!"); Thread.Sleep ( +); Selector.Select();//Just starting when there is no client connection, it will clog up hereset<selectionkey> keys = Selector.selectedkeys (); iterator<selectionkey> Iterator = Keys.iterator (); while(Iterator.hasnext ()) {Selectionkey key = Iterator.next (); Iterator.remove ();//In order to prevent repeating iterations if(Key.isacceptable ()) {Serversocketchannel Serversocketchannel = (serversocketchannel) key.channel (); Socketchannel Socketchannel = serversocketchannel.accept ();//New ConnectionSystem. out. println ("Client accept!"+ Socketchannel); Socketchannel.configureblocking (false);//Socketchannel.register (selector, //Selectionkey.op_write);//Register WRITESocketchannel.register (selector, Selectionkey.op_read, Bytebuffer.allocate (1024x768));//Register Read}Else if(Key.iswritable ()) {//writeSocketchannel Socketchannel = (socketchannel) key.channel ();//Get the channel to communicate with the clientString sendmsg ="Hello world!"; Bytebuffer WriteBuffer = Bytebuffer.wrap (Sendmsg.getbytes ()); System. out. println ("Server Send msg==="+ sendmsg); Socketchannel.write (WriteBuffer); Key.cancel (); }Else if(Key.isreadable ()) {//ReadSocketchannel Socketchannel = (socketchannel) key.channel ();//Get the channel to communicate with the clientBytebuffer Readbuffer = (bytebuffer) key.attachment ();//Get and empty buffersReadbuffer.clear ();LongBytesread = Socketchannel.read (Readbuffer);//Read the information to get the number of bytes read if(Bytesread! =-1) {Readbuffer.flip ();//Ready to readString receivemsg ="";//Convert bytes to Strings while(Readbuffer.hasremaining ()) {receivemsg + = string.valueof (Char) Readbuffer.Get()); }?????? Thread.Sleep ( the);//server waits 5 seconds before printing, but the client does not wait forSystem. out. println ("Server Receive msg==="+ receivemsg); } key.cancel (); } } } } Public Static void Main(string[] args) throws Exception {NewSocketchannelserver (); }}
After the service-side code is run, the program listens until a client request is received. The results are as follows:
Waitting connet ...
Client code:
Public classsocketchannelclient {PrivateString host ="127.0.0.1";//IP to be sent to the server Private intPort =8000;//port to be sent to the server Public socketchannelclient() throws IOException {Socketchannel sc = Socketchannel.open (NewInetsocketaddress (host, port));//Open a socketchannel and connect to the serverSc.configureblocking (false);//Accept messages from serverBytebuffer Readbuffer = Bytebuffer.allocate ( -); Sc.read (Readbuffer); Readbuffer.flip ();//Ready to readString receivemsg ="";//Convert bytes to Strings while(Readbuffer.hasremaining ()) {receivemsg + = string.valueof (Char) Readbuffer.Get()); } System. out. println ("Client Receive msg==="+ receivemsg);//Send message to serverString sendmsg ="I am a coder."; Bytebuffer WriteBuffer = Bytebuffer.wrap (Sendmsg.getbytes ()); System. out. println ("Client Send msg==="+ sendmsg); Sc.write (WriteBuffer); Sc.close (); } Public Static void Main(string[] args) throws IOException {NewSocketchannelclient (); }}
Our client has done 2 things, one is to accept the service side message, one is to send messages to the server. Since we are testing multiple clients to connect to the same server, we need to run the client code multiple times. Here we run two times (called Client 1, Client 2), view the server console, not more than 5 seconds when the following results show that the connection is successful. It is important to note that the last sentence prints the waiting accept! again, stating that it has not been waiting for the client to send the request, but continues to listen for the request, which is not blocked:
Waiting accept!
Client accept!java.nio.channels.socketchannel[connected local=/127.0.0.1:8000 remote=/127.0.0.1:59481]
Waiting accept!
At this point, each client console is as follows, successfully receiving a message from the server and sending it to the server, immediately releasing the thread and not waiting for the server to execute:
Client Receive msg===
Client send msg===i am a coder.
After returning to the server console,5 seconds, we will print the request we received:
Waiting accept!
Client accept!java.nio.channels.socketchannel[connected local=/127.0.0.1:8000 remote=/127.0.0.1:59481]
Waiting accept!
Server Receive msg===i am a coder.
Waiting accept!
Client accept!java.nio.channels.socketchannel[connected local=/127.0.0.1:8000 remote=/127.0.0.1:59485]
Waiting accept!
Server Receive msg===i am a coder.
Waiting accept!
Here we see a request to handle 2 clients. In the server-side code, we can register write to achieve the requirement to write data to the client.
Java thousand ask _02 basic use (012) _ How to write non-blocking Socketchannel program