Java NiO adds new socketchannel, serversocketchannel, and other classes to provide a high-performance serverProgram. Socketchannel and serversocketchannel can work in non-blocking mode. They are all selectable classes. Java NiO is recommended when building servers or middleware.
In traditional network programming, we usually use a dedicated thread to process a socket connection. By using NiO, one or few socket threads can process thousands of active socket connections.
Generally, an instance of serversocketchannel is obtained through serversocketchannel. open (), and a socketchannel instance is obtained through socketchannel. Open or serversocketchannel. Accept. To enable serversocketchannel or socketchannel to operate in non-blocking mode, you can call
Serversocketchannel. configureblocking (false );
Or
Socketchannel. configureblocking (false );
Statement. Generally, the server can use a non-blocking serversocketchannel, so that the server program can easily process multiple socket threads at the same time.
let's take a comprehensive example. This example uses serversocketchannel and socketchannel to develop a non-blocking echo server program that can process multiple threads. See example 12-14.
[Program Source Code ]
1 // ================================= program discription ==================== ======= 2 // program name: example 12-14: socketchanneldemo. java3 // program purpose: learn Java NiO # socketchannel4 // ================================== ============================ 5 6 7 Import Java. NIO. bytebuffer; 8 Import Java. NIO. channels. serversocketchannel; 9 Import Java. NIO. channels. socketchannel; 10 Import Java. NIO. channels. selector; 11 import Java. NIO. channels. selec Tionkey; 12 Import Java. NIO. channels. selectablechannel; 13 14 Import java.net. socket; 15 Import java.net. serversocket; 16 Import java.net. inetsocketaddress; 17 import Java. util. iterator; 1819 public class socketchanneldemo 20 21 {22 public static int port_number = 23; // listening port 23 serversocketchannel serverchannel; 24 serversocket; 25 selector; 26 private bytebuffer buffer = bytebuffer. A Locatedirect (1024); 27 28 public static void main (string [] ARGs) 29 throws exception30 {31 socketchanneldemo Server = new socketchanneldemo (); 32 server. init (ARGs); 33 server. startwork (); 34} 35 36 37 public void Init (string [] argv) throws exception38 {39 int Port = port_number; 40 41 if (argv. length> 0) {42 Port = integer. parseint (argv [0]); 43} 44 45 system. out. println ("listening on port" + por T); 46 47 // assign a serversocketchannel48 serverchannel = serversocketchannel. open (); 49 // obtain a socket50 serversocket = serverchannel from the serversocketchannel. socket (); 51 // generate a selector52 selector = selector. open (); 53 54 // bind the socket to port 55 serversocket. BIND (New inetsocketaddress (port); 56 // serverchannel is not a bolck57 serverchannel. configureblocking (false); 58 59 // register serversocetchannel60 server through Selector Channel. register (selector, selectionkey. op_accept); 61 62} 63 64 public void startwork () throws exception 65 66 {67 while (true) {68 69 int n = selector. select (); // obtain the number of IO-ready channels 70 71 If (n = 0) {72 continue; // No channel is ready, continue execution 73} 74 75 // use an iterator to return selectedkeys76 iterator it = selector. selectedkeys (). iterator (); 77 78 // process each selectionkey79 while (it. hasnext () {80 selectionkey Key = (selectionkey) it. next (); 8182 // determine whether a new connection reaches 83 If (key. isacceptable () {84 // return serversocketchannel85 serversocketchannel Server = (serversocketchannel) Key of selectionkey. channel (); 86 socketchannel channel = server. accept (); 87 88 registerchannel (selector, channel, 89 selectionkey. op_read); 90 91 dowork (Channel); 92} 93 94 // determine whether data exists. In this channel, 95 If (key. isreadable () {96 97 processdata (key); 98 99} 100 101 // Delete selectedkeys102 it. remove (); 103} 104} 105} 106 protected void registerchannel (selector, 107 selectablechannel channel, int OPS) 108 throws exception109 {110 if (Channel = NULL) {111 return; 112} 113 114 115 channel. configureblocking (false); 116 117 channel. register (selector, OPS); 118} 119 120 // process received data 121 protected void processdata (selectionkey key) 122 throws excep Tion123 {124 125 126 socketchannel = (socketchannel) Key. channel (); 127 int count; 128 129 buffer. clear (); // clear buffer130 131 // read all data 132 while (COUNT = socketchannel. read (buffer)> 0) {133 buffer. flip (); 134135 // send the data, don't assume it goes all at once136 while (buffer. hasremaining () 137 {138 // If you receive the Enter key, add [Echo] $139 If (buffer. get () = (char) 13) 140 {141 buffer. CLEA R (); 142 buffer. put ("[Echo] $ ". getbytes (); 143 buffer. flip (); 144 145} 146 socketchannel. write (buffer); // write data in the socket 147} 148 149 buffer. clear (); // clear buffer150} 151 152 If (count <0) {153 // count <0, indicating that 154 socketchannel has been read. close (); 155} 156 157 158 159 private void dowork (socketchannel channel) throws exception160 {161 buffer. clear (); 162 buffer. put ("Hello, I am working, please input some thing, D I will echo to you! [Echo] $ ". getbytes (); 163 buffer. Flip (); 164 channel. Write (buffer); 165} 166 167} |
Use: run this program, and then enter the command Telnet localhost 23 on the console.
[Program output result] 12-1 is shown.
Figure 12-1 output result
[Program annotation]
The explanation of the program is included in the program. Here we summarize the process of using serversocket channel to develop the server program:
(1) assign a serversocketchannel.
(2) Obtain a serversocket from the serversocketchannel.
(3) generate a selector instance.
(4) bind serversocket to the port.
(5) set serversocketchannel to non-block mode (optional ).
(6) Register serversocetchannel in selector.
(7) use an infinite loop statement to check whether the selector has an I/O ready channel. If yes, the corresponding processing is executed. If no, the loop continues.
Knot
In this chapter, we mainly introduce network programming in Java. Java is a network at the beginning.Programming LanguageLater, it was applied to various aspects. Therefore, network programming in Java is far more convenient than in C/C ++.
We introduced several important classes in network programming, such as inetaddress, URL, urlconnection, socket, serversocket, datagramsocket, datagrampacket, and multicastsocket. These classes contain all the content for basic network programming. To skillfully apply these classes, you must exercise more.
Socket-based programming is basically the Client/Server mode. We introduce the steps for writing this mode in detail. In terms of instances, we provide a TCP-based Socket Client/Server program. Correspondingly, we also provide UDP-based client/server programs. The two models are very similar. In fact, this is the general mode for writing client/server programs. (T111)