Java Socket NiO Detailed (GO)

Source: Internet
Author: User

What does the Java selector (Selector) do for you? 2009-01-12 22:21jsptdut | Category: Java-related | Browse 8,901 times title, do not post API, above the write I do not understand hope that you can give me a familiar example and Serversocketchannel this class, Java.nio This bag of things, I see the API also do not understand ~ Ah, annoyed AH is you ah ~ssc.register (selector, selectionkey.op_accept); What does the second parameter of this method mean?  And this Selectionkey.op_readapi says: The operation set bit for the socket accept operation. Do not understand ~ ~ ~ Hehe, I come to tell you, as to the example code in my answer record has. You flip it yourself, it's a BBS chat room written by NiO to a student. In the process of communicating with NiO I give you the following scenario simulation: 1. School (Serversocketchannel) 2. School Academic Office (Selector) 3. Teacher (ServerSocket) 4. Student (Socketchannel) 5. Employee Number/Student number (Selectionkey) school: equivalent to our web application, once the school starts, the school will not stop, keep running until the end of the semester; to start the school: Serversocketchannel ssc= Serversocketchannel.open ();//Create a new NIO channel ssc.configureblocking (FALSE);//Make the channel non-blocking teacher: the equivalent of the server socket, a teacher for multiple students, Many students ask the teacher for advice, and the teacher will answer each one. and the school to normal operation of course not to be a teacher, so before the start of school, must first hire a professional teacher to teach ServerSocket SS = Ssc.socket ();//Create a port for the NIO channel-based socket connection//new socket channel Ss.bind ( New Inetsocketaddress ("127.0.0.1", ServerPort)); School Administration Office: teachers have, but need to have a department of teachers and students to do a unified management, if you go to a school to find a person, it is not found, you can tell the dean, that the person is a student or teacher, is the teacher's words employee number teacher name Number, is the student's word number and name is how much, The dean's office will find out where he is. The NIO channel is selected to bind to the selector, and of course the primary key assigned after the binding is Skey SelectiOnKey skey = Ssc.register (selector, selectionkey.op_accept); After the SSC registered the selector, the teacher ServerSocket under it also entered the staff book. So the teacher's number is Skey students: schools, teachers, the office of the Administration has, now can recruit! If there is a student to enroll: while (TRUE) {//unless the semester ends, otherwise wait for the student int num = Selector.select ();//Get the channel within the event of a selector concern, meaning how many students report if (NUM<1) { Continue Set Selectedkeys = Selector.selectedkeys ();//Get a collection of care events within the channel, where the collection is a collection of teacher and student numbers, if key is a student, that is the old student to ask questions, if key is the teacher's, That's the admissions office teacher with a new born registered Iterator it = selectedkeys.iterator (); while (It.hasnext ()) {//Traverse each key (student key and teacher key) ...} ... Since there are students to report, there are two possibilities, one is the admission teacher with the freshmen to register, one is Laosheng to ask questions. The upper while (It.hasnext ()) body can be written like this: while (It.hasnext ()) {//Traversal each event try{selectionkey key = (Selectionkey) it.next ();//Get this student first The number key//Judge is the freshman report or the Laosheng question if ((Key.readyops () & selectionkey.op_accept) = = selectionkey.op_accept) {// This is the admission teacher's key description is the freshman registration, the first to find the admission teacher, and then by the admissions teacher to find new students, you can give the new student registration number Serversocketchannel Serverchanel = (serversocketchannel) Key.channel (); Through key to the school and teachers found//from the Serversocketchannel to create a connection with the client Socketchannel have a teacher to students, it is impossible for me to teach computer, to a want to learn Bruce Lee's all let him sign up Socketchannel SC= Serverchanel.accept (); Student Registration Successful sc.configureblocking (FALSE); Register a new connection to the selector, the freshman is received after the registration of a newly-learned number Selectionkey NewKey = Sc.register (selector, selectionkey.op_read); Registration number is successful and the student's permission is assigned It.remove (); Freshman registration task completed, hehe System.out.println ("Got connection from" +SC); else//Read the client data event, at which point the client sends data over the client event this is the old student to ask the question. if ((Key.readyops () & selectionkey.op_read) = = Selectionkey.op_read) {//Read data, accept student's question Socketchannel sc = ( Socketchannel) Key.channel (); Know who asked the question by the number//below accept the question int bytesechoed = 0; while ((bytesechoed = Sc.read (echobuffer)) > 0) {System.out.println ("bytesechoed:" +bytesechoed);} Echobuffer.flip (); System.out.println ("Limet:" +echobuffer.limit ()); byte [] content = new Byte[echobuffer.limit ()]; Echobuffer.get (content); String Result=new string (content); DoPost (RESULT,SC); The corresponding teacher will do the answer, the details of their own to write it Echobuffer.clear (); It.remove (); Task completion, remember that the same is the same, to remove, or the next time another task, will die loop}}catch (Exception e) {}}} supplement your supplement: Ssc.register (selector, selectionkey.op_ ACCEPT); This method is to bind the SSC registration to the selector selector so next time you want to find SSC,Or whether an object is a SSC can be found by selector, and the lookup is obtained by judging the key of SSC. As for the second parameter selectionkey.op_accept you can understand the key type of SSC or operation permissions if SSC is a school teacher, then the teacher has the op_ after the binding succeeds. The permission of accept or his key type is selectionkey.op_accept accept is accepted, this is not much like socket programming in the Accept () method? Yes, yes, it is through this parameter that we give the teacher admission and students to register the permission. And what about the students? He has a permission of Selectionkey.op_read to send and receive read messages, that is, the right to ask questions, so he can not help other students register. So you go back up and take a closer look at the while structure to make the following judgments: if ((Key.readyops () & selectionkey.op_accept) = = selectionkey.op_accept) {...} obviously, The person who has permission to accept can only be a teacher, what will the teacher find the academic office? That must be he is the admissions office, recruit a student to sign up to register. Then, immediately to this new connected client assigned a keyselectionkey NewKey = Sc.register (selector, selectionkey.op_read); Look, this is only for him op_read, not accept oh another if ElseIf ((Key.readyops () & selectionkey.op_read) = = Selectionkey.op_read) {//Obviously, This is the student, because all the people who bring op_read have been brought over by the admissions office before the registration. Do you have any idea? Questioner comments Thank you, speak very clearly ~ I would like to give you points, but I do not have a lot of

Java Socket NiO Detailed (GO)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.