Use asynchronous input-output flow preparation process Socket Communications

  Abstract: The use of asynchronous input-output flow preparation process Socket Communications 

  : From: ytjcopy@china.com Yang Jian Abstract: code, as "Merlin" J2SE1.4 brought some exciting new features, such as a regular expression of support, asynchronous input-output flow channel ( Channel), Character Set, etc. Although this version is still in the testing stage, but these new features make the developers are eager. released in the Merlin before, asynchronous input and output streams of just C, C + + programmers the special weapons; Merlin in the introduction of asynchronous input-output mechanism, Java programmers can also use a lot of it is concise quality of the code. paper will describe how to use asynchronous input-output flow process to prepare Socket Communication Program. 

  Sync?    Asynchronous input-output mechanism for the introduction of the Merlin before, the preparation process is more cumbersome Socket work because the input and output must be synchronized so that the multi-client client / server model to use multi-threading. Each of which is connected Customers are allocated a thread to handle input and output. this is a result of the problems can be imagined. programmers had to in order to avoid deadlock, thread-safety issues, a lot of coding and testing. lot of people Why not complain about the introduction of Java asynchronous input-output mechanism. comparison official explanation is that any application program interface, the introduction, must be compatible with any platform. because Java is cross-platform. then support asynchronous input-output mechanisms operating platform is not all. since the Java 2 Platform, the isolated J2SE, J2ME, J2EE three different types of application programming interfaces in order to meet different application development. Java standards makers are aware of the problem , and supported asynchronous input-output mechanisms operating platform in the current operating platform in a mainstream status. therefore, Jdk (J2SE), the fifth release introduces asynchronous input-output mechanism. 

  Socket Communications process before the process design, general client and the server-side program design as follows: 

  Server: 
  / / Server monitor thread 
  While (true) ( 
………….
  Socket clientSocket; 
  ClientSocket = socket.accept (); / / Socket obtain customer requests, and if there is no / / customer requests to connect, thread here obstruction 
  / / Socket structure with the input and output flow 
  PrintStream os = new PrintStream (new 
  BufferedOutputStream (clientSocket.getOutputStream (), 
  1024), false); 
  BufferedReader is = new BufferedReader (new 
  InputStreamReader (clientSocket.getInputStream ())); 
  / / Create customer conversational threads, input and output control, synchronization mechanism 
  New ClientSession (); 
…….
  ) 

  Client: 
…………
  ClientSocket = new Socket (HOSTNAME, LISTENPORT); / / socket connects to the server 
  / / Socket structure with the input and output flow 
  PrintStream os = new PrintStream (new 
  BufferedOutputStream (clientSocket.getOutputStream (), 
  1024), false); 
  BufferedReader is = new BufferedReader (new 
  InputStreamReader (clientSocket.getInputStream ())); 
  / / Input-output control 
…….

  Just use the code above paragraph Socket synchronization mechanism to prepare a framework for the process of communication, in fact to consider issues to be more complicated (Interested readers can refer to my article "Internet Real-time Communication System Design and Implementation").    Such a framework will be out, only to the use of asynchronous mechanism to bring about a process of communication Socket comparison.    Below will introduce the use of asynchronous mechanism of the design process. 

  Asynchronous input-output flow prepared Socket Communication Program in the process of accession to the Merlin used to achieve asynchronous input-output mechanism for application program interface kits: java.nio (new input-output package, definition of a lot of basic types of buffer (Buffer) ), java.nio.channels (access and choice, etc., for asynchronous input-output), java.nio.charset (characters codecs).    Channel (Channel) first choice (Selector) registered their interest in the incident, when the corresponding time of the incident, then by selecting the selector button (SelectionKey) notification has been registered crossing.    Then access the information will need to be addressed through the buffer (Buffer) packaging, encoding / decoding, complete input-output control. 

  Channel description: 
  Here are introduced ServerSocketChannel and SocketChannel. They are optional (selectable) channels, respectively, can work in both synchronous and asynchronous modes (Note that the choice was not referring here can choose two ways of work, but that can be registered their interest in the choice of events).    Can be used channel.configureBlocking (Boolean) to set up its working methods.    And the previous version of the API, compared to the equivalent ServerSocketChannel ServerSocket (ServerSocketChannel Packaging, a ServerSocket), and the equivalent SocketChannel Socket (SocketChannel Packaging, a Socket).    When working in the channel synchronous manner, and the programming method similar to the previous, where the main work on asynchronous mode. 

  The so-called asynchronous input-output mechanism, it is that in dealing with input and output, without waiting for input and output have been disposed of the return.    It is synonymous with asynchronous non-blocking (None Blocking).    On the server end, ServerSocketChannel static function open () returns an example serverChl.    The channel then called serverChl.socket (). Bind () bundled with a server ports, and register call (Selector sel, SelectionKey.OP_ACCEPT) registered OP_ACCEPT incident to a selector (ServerSocketChannel can only registered OP_ACCEPT Incident).    When a client requests to connect, will inform the choice of a channel connecting customers request, we can carry out the corresponding input and output control in the client, clientChl registered their interest in the case after the incident (which can be OP_CONNECT, OP_READ, OP_WRITE the combination), calls clientChl.connect (InetSocketAddress) connects to the server and then treated accordingly.    Note that the connection is asynchronous, that is, and will continue to implement immediately return behind the code. 

  Selector and selection key description: 
  Selector (Selector) role is: will be interested in the events Add channel queue, rather than immediately to the application, registration, etc., have access to their own request in these cases.    In other words, it will be ready for selection report has been ready for a channel, and in accordance with the FIFO order.    Well, the choice of what to report?    Select (SelectionKey).    Select the role of which is the channel that has been prepared for and ready to do.    Maybe you would immediately think, it must have registered interest in the channel events.    Yes, for example, the server-side serverChl, key.isAcceptable can call () to notify serverChl a client request.    The corresponding function is also available in: SelectionKey.isReadable (), SelectionKey.isWritable ().    General, in a circle of interested Polling events (Refer to the following specific code).    If there is no channel selector has been registered in the incident, calling Selector.select () will be blocked until the case so far.    In addition, you can call selectNow () or select (long timeout).    Immediately return to the former, no incidents of return 0; timeout after the latter waiting for the return.    A choice of up to 63 channels at the same time with the use of registration. 
  Application examples: 
  Below are using asynchronous input-output mechanism to achieve the client / server examples of procedures - procedures list 1 (Due to space limitations, only the server is achieved, the reader can refer to the realization of client code): 

  Class Diagram procedures 

  (Public class NBlockingServer 
  Int port = 8000; 
  Int BUFFERSIZE = 1024; 
  Selector selector = null; 
  ServerSocketChannel serverChannel = null; 
  HashMap clientChannelMap = null; / / used to store each client connection socket and the corresponding channel 

  Public NBlockingServer (int port) ( 
  This.clientChannelMap = new HashMap (); 
  This.port = port; 
  ) 

  Public void initialize () throws IOException ( 
  / / Initialization, were examples of a choice, a choice of server-side channel 
  This.selector = Selector.open (); 
  This.serverChannel = ServerSocketChannel.open (); 
  This.serverChannel.configureBlocking (false); 
  InetAddress localhost = InetAddress.getLocalHost (); 
  InetSocketAddress isa = new InetSocketAddress (localhost, this.port); 
  This.serverChannel.socket (). Bind (isa); / / the socket can be bound to a particular server ports 
  ) 
  / / At the end of the release of resources 
  Public void finalize () throws IOException ( 
  This.serverChannel.close (); 
  This.selector.close (); 
  ) 
  / / Read the information byte buffer decoder 
  Public String decode (ByteBuffer byteBuffer) throws 
  CharacterCodingException ( 
  Charset charset = Charset.forName ( "ISO-8859-1"); 
  CharsetDecoder decoder = charset.newDecoder (); 
  CharBuffer charBuffer = decoder.decode (byteBuffer); 
  String result = charBuffer.toString (); 
  Return result; 
  ) 
  / / Monitor port, when the channel ready in time for the corresponding operation 
  Public void portListening () throws IOException, InterruptedException ( 
  / / Server-side channel registration OP_ACCEPT incident 
  SelectionKey acceptKey = this.serverChannel.register (this.selector, 
  SelectionKey.OP_ACCEPT); 
  / / When a registered time of the incident, select () return value will be greater than 0 
  While (acceptKey.selector (). Select ()> 0) ( 
  System.out.println ( "event happened"); 
  / / Get all has been prepared all the options button 
  Set readyKeys = this.selector.selectedKeys (); 
  / / Use iterators on the button to select polling 
  Iterator i = readyKeys.iterator (); 
  While (i 
  Else if (key.isReadable ()) (/ / If it is ready to channel Reading events 
  System.out.println ( "Readable"); 
  / / Select the corresponding channel and Sockets 
  SelectableChannel nextReady = 
  (SelectableChannel) key.channel (); 
  Socket socket = (Socket) key.attachment (); 
  / / Handle the incident, and processing method has been encapsulated in the category ClientChInstance 
  This.readFromChannel (socket.getChannel (), 
(ClientChInstance)
  This.clientChannelMap.get (socket)); 
  ) 
  Else if (key.isWritable ()) (/ / If it is ready to write channel events 
  System.out.println ( "writeable"); 
  / / The socket post-processing methods Ibid. 
  Socket socket = (Socket) key.attachment (); 
  SocketChannel channel = (SocketChannel) 
  Socket.getChannel (); 
  This.writeToChannel (channel, "This is from server!"); 
  ) 
  ) 
  ) 
  ) 
  / / Write operation of the channel 
  Public void writeToChannel (SocketChannel channel, String message) 
  Throws IOException ( 
  ByteBuffer buf = ByteBuffer.wrap (message.getBytes ()); 
  Int nbytes = channel.write (buf); 
  ) 
  / / Read operation of the channel 
  Public void readFromChannel (SocketChannel channel, ClientChInstance clientInstance) 
  Throws IOException, InterruptedException ( 
  ByteBuffer byteBuffer = ByteBuffer.allocate (BUFFERSIZE); 
  Int nbytes = channel.read (byteBuffer); 
  ByteBuffer.flip (); 
  String result = this.decode (byteBuffer); 
  / / When the client issued the "@ exit" from the order, shut down its channel 
  If (result.indexOf ( "@ exit")> = 0) ( 
  Channel.close (); 
  ) 
  Else ( 
  ClientInstance.append (result.toString ()); 
  / / Read his finished, the implementation of the corresponding operation 
  If (result.indexOf ( "\ n")> = 0) ( 
  System.out.println ( "client input" + result); 
  ClientInstance.execute (); 
  ) 
  ) 
  ) 
  / / Packaging such a client on how to operate the channel, can be realized through specific Heavy execute () method 
  (Public class ClientChInstance 
  SocketChannel channel; 
  StringBuffer buffer = new StringBuffer (); 
  Public ClientChInstance (SocketChannel channel) ( 
  This.channel = channel; 
  ) 
  Public void execute () throws IOException ( 
  String message = "This is response after reading from channel!"; 
  WriteToChannel (this.channel, message); 
  Buffer = new StringBuffer (); 
  ) 
  / / When his party did not at the end of the current buffer at the end of the word channeling 
  Public void append (String values) ( 
  Buffer.append (values); 
  ) 
  ) 

  / / Main program 
  Public static void main (String [] args) ( 
  NBlockingServer nbServer = new NBlockingServer (8000); 
  Try ( 
  NbServer.initialize (); 
  ) Catch (Exception e) ( 
  E.printStackTrace (); 
  System.exit (-1); 
  ) 
  Try ( 
  NbServer.portListening (); 
  ) 
  Catch (Exception e) ( 
  E.printStackTrace (); 
  ) 
  ) 
  ) 

  A list of procedures 

  Summary: 
  From the above procedures, we can see that the server did not introduce unnecessary completed the multi-threading, the client / server model.    The procedure used in the correction mode (CALLBACK), the careful reader should have noticed.    It must be noted that, please do not original input-output package with the addition of new input-output package mix, as consideration for a number of reasons, these two packages is not compatible.    That is to use the access route for input and output buffer complete control.    The procedure in Windows2000, J2SE1.4, tested successfully with telnet. 

  References: 

  "JavaTM 2 Platform, Standard Edition, v 1.4.0 API Specification" 

  About the author Yang Jian, China and South Africa University of Technology Computer Science and Technology Postgraduate, participated in a large-scale MIS system development, such as construction sites, are now working on Java technology.    Email: ytjcopy@china.com.    Java, java, J2SE, j2se, J2EE, j2ee, J2ME, j2me, ejb, ejb3, JBOSS, jboss, spring, hibernate, jdo, struts, webwork, ajax, AJAX, mysql, MySQL, Oracle, Weblogic, Websphere, scjp, scjd 
  ↑ Back 

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • DotNetKicks
  • DZone
  • Netvouz
  • Propeller

Tags: , ,

Releated Java Articles

Comments

Leave a Reply