Java-mina (NIO framework)

Source: Internet
Author: User

Mina is the concrete realization of NIO. is currently a relatively efficient and popular NIO framework.

Here is a simple demo of communicating using Mina, followed by a simple framework for writing an RPC with Mina. Mina mainly include: (using the Mina version for 2.0.0.M4 Core, specifically visible official website) Mina also sub-server and client (this is sure ...) Where the server is: Niosocketacceptor client: Niosocketconnector is similar to the socket server and client socket. In addition to these basic communications, there are some operations classes that can be used to handle communication. is the filter on the client and server side. These filter can be used for decoding, encoding, can configure the log information, you can set the type of serialization, and so on. In addition, the client and the server can be bound to a iohnadler, to handle the connection session in open, receive information, close the status of the action can be carried out.

Now it's time to use Mina to perform a demo of a simple client upload file: The demo implementation idea is:The client is connected to the server, and the client transmits a certain size of file content to the server each time. (Byte way), then the server receives these bytes, outputs them, and forms the file. After the client sends, pass a complete flag, here can pass a string "Finish", then the server received this end flag, after the end of the write file, then transmit a successful flag to the client, (the string "Success") and then the client closes the connection.
Server: The code is relatively simple. Java code
  1. Import java.net.InetSocketAddress;
  2. Import Org.apache.mina.filter.codec.ProtocolCodecFilter;
  3. Import Org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
  4. Import Org.apache.mina.filter.logging.LoggingFilter;
  5. Import Org.apache.mina.transport.socket.nio.NioSocketAcceptor;
  6. Public class Main {
  7. private static final int PORT = 8080;
  8. public static void Main (string[] args) throws Exception {
  9. //Service-side instances
  10. Niosocketacceptor accept=New Niosocketacceptor ();
  11. //Add Filter,codec to serialization mode.  This is the object serialization method, which means that the object is passed.
  12. Accept.getfilterchain (). AddLast ("codec",
  13. New Protocolcodecfilter (new Objectserializationcodecfactory ()));
  14. //Add filter, log information
  15. Accept.getfilterchain (). AddLast ("Logging", new Loggingfilter ());
  16. //Set handler on the service side
  17. Accept.sethandler (new Fileuploadhandler ());
  18. //Bind IP
  19. Accept.bind (new Inetsocketaddress (PORT));
  20. System.out.println ("Upload server started.");
  21. }
  22. }
So simple to complete the service side of the implementation, in fact, can be more complex, where the log and code can be written and generated on their own, here only use Mina. Then the handler on the server side. Java code
  1. Import Java.io.BufferedOutputStream;
  2. Import Java.io.File;
  3. Import Java.io.FileOutputStream;
  4. Import Org.apache.commons.logging.Log;
  5. Import Org.apache.commons.logging.LogFactory;
  6. Import Org.apache.mina.core.service.IoHandlerAdapter;
  7. Import org.apache.mina.core.session.IoSession;
  8. Public class Fileuploadhandler extends Iohandleradapter {
  9. private Bufferedoutputstream out;
  10. private int count;
  11. private String FileName = "D:/log/test.jpg";
  12. private static final log log = Logfactory.getlog (Fileuploadhandler.   Class);
  13. public void Sessionopened (iosession session) throws Exception {
  14. SYSTEM.OUT.PRINTLN ("Server Open");
  15. }
  16. public void Exceptioncaught (iosession session, Throwable cause)
  17. throws Exception {
  18. System.out.println ("Exception");
  19. Session.close (true);
  20. Super.exceptioncaught (session, cause);
  21. }
  22. public void Messagereceived (iosession session, Object message) {
  23. SYSTEM.OUT.PRINTLN ("Server received");
  24. try {
  25. if (message instanceof fileuploadrequest) {
  26. //fileuploadrequest is used in the pass-through process.
  27. Fileuploadrequest request = (fileuploadrequest) message;
  28. System.out.println (Request.getfilename ());
  29. if (out = = null) {
  30. //Create a new file input object Bufferedoutputstream, and define the location of the new file arbitrarily.
  31. out = new Bufferedoutputstream (new FileOutputStream (
  32. "d:/log/" + Request.getfilename ()));
  33. Out.write (Request.getfilecontent ());
  34. } Else {
  35. Out.write (Request.getfilecontent ());
  36. }
  37. Count + = Request.getfilecontent (). length;
  38. } Else if (message instanceof String) {
  39. if ((String) message). Equals ("Finish")) {
  40. System.out.println ("size is" +count);
  41. //This is the file transfer after the file is to be flush and close otherwise the files are not complete.
  42. Out.flush ();
  43. Out.close ();
  44. //Receipt client information, upload file successful
  45. Session.write ("Success");
  46. }
  47. }
  48. } catch (Exception e) {
  49. E.printstacktrace ();
  50. }
  51. }
  52. public void Sessionclosed (iosession session) throws Exception {
  53. SYSTEM.OUT.PRINTLN ("server Session Close");
  54. }
  55. }
All handler inherit Iohandleradapter and can view Iohandleradapter, which includes several methods for session state. You can overload it on demand. Then there is the common do:fileuploadrequest simple Pojo Java code that is used for transmission.
  1. Import java.io.Serializable;
  2. Public class Fileuploadrequest implements Serializable {
  3. private String hostname;
  4. private String filename;
  5. private byte[] filecontent;
  6. Public String GetHostName () {
  7. return hostname;
  8. }
  9. public void SetHostName (String hostname) {
  10. this.hostname = hostname;
  11. }
  12. Public String GetFileName () {
  13. return filename;
  14. }
  15. public void Setfilename (String filename) {
  16. this.filename = filename;
  17. }
  18. public byte[] Getfilecontent () {
  19. return filecontent;
  20. }
  21. public void Setfilecontent (byte[] filecontent) {
  22. this.filecontent = filecontent;
  23. }
  24. }
Next look at the client implementation, also very simple: Java code
  1. Import Java.io.File;
  2. Import Java.io.FileInputStream;
  3. Import java.io.IOException;
  4. Import java.net.InetSocketAddress;
  5. Import Nio.upload.server.FileUploadRequest;
  6. Import Org.apache.mina.core.future.ConnectFuture;
  7. Import org.apache.mina.core.session.IoSession;
  8. Import Org.apache.mina.filter.codec.ProtocolCodecFilter;
  9. Import Org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
  10. Import Org.apache.mina.filter.logging.LoggingFilter;
  11. Import Org.apache.mina.transport.socket.nio.NioSocketConnector;
  12. Public class Mainclient {
  13. private static final int PORT = 8080;
  14. /** 
  15. * @param args
  16. * @throws IOException
  17. */
  18. public static void Main (string[] args) throws Exception {
  19. //client-side implementation
  20. Niosocketconnector connector = new Niosocketconnector ();
  21. Connector.getfilterchain (). AddLast ("codec",
  22. New Protocolcodecfilter (new Objectserializationcodecfactory ()));
  23. Connector.getfilterchain (). AddLast ("Logging", new Loggingfilter ());
  24. Fileuploadclienthandler h = new Fileuploadclienthandler ();
  25. Connector.sethandler (h);
  26. //This sentence needs to be added, otherwise you cannot call the following readfuture to read the information returned from the session to the server.
  27. Connector.getsessionconfig (). Setusereadoperation (true);
  28. Connectfuture CF = Connector.connect (new inetsocketaddress ("localhost",
  29. PORT));
  30. Iosession session;
  31. //wait for the connection to succeed
  32. Cf.awaituninterruptibly ();
  33. Session = Cf.getsession ();
  34. SYSTEM.OUT.PRINTLN ("client send Begin");
  35. //Pass file start
  36. String fileName = "Test.jpg";
  37. FileInputStream FIS = new FileInputStream (new File);
  38. byte[] A = new byte[* 4];
  39. Fileuploadrequest request = new Fileuploadrequest ();
  40. Request.setfilename (FileName);
  41. Request.sethostname ("localhost");
  42. While (Fis.read (A, 0, a.length)! =-1) {
  43. Request.setfilecontent (a);
  44. //Like session to write information for the server to obtain
  45. Session.write (Request);
  46. }
  47. //Send the completed flag
  48. Session.write (new String ("Finish"));
  49. SYSTEM.OUT.PRINTLN ("Client send finished and wait success");
  50. //Connect the above to get information on the server
  51. Object result = Session.read (). awaituninterruptibly (). GetMessage ();
  52. if (Result.equals ("Success")) {
  53. System.out.println ("success!");
  54. //Close client
  55. Connector.dispose ();
  56. }
  57. }
  58. }
The implementation of the client handler. Java code
  1. Import Org.apache.mina.core.service.IoHandlerAdapter;
  2. Import org.apache.mina.core.session.IoSession;
  3. Public class Fileuploadclienthandler extends Iohandleradapter {
  4. public void Sessionopened (iosession session) throws Exception {
  5. SYSTEM.OUT.PRINTLN ("client Open");
  6. }
  7. public void Sessionclosed (iosession session) throws Exception {
  8. SYSTEM.OUT.PRINTLN ("client session close");
  9. }
  10. public void Messagereceived (iosession session, Object message)
  11. throws Exception {
  12. System.out.println ("thr result is" + message);
  13. }
  14. }

Java-mina (NIO framework)

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.