java-Communication Stocket Plugin Mina instance

Source: Internet
Author: User

Mina is the concrete realization of NIO. is currently the more efficient and popular nio (non-blocking I/O) framework

Mina mainly includes:

Where the server is: Niosocketacceptor client: Niosocketconnector

Using Mina to carry out a simple client upload file Demo implementation: Demo Implementation of the idea is: the client and the server to establish a connection, the client each time to the server to transfer a certain size of file content. (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.
Importjava.net.InetSocketAddress;ImportOrg.apache.mina.filter.codec.ProtocolCodecFilter;Importorg.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;ImportOrg.apache.mina.filter.logging.LoggingFilter;ImportOrg.apache.mina.transport.socket.nio.NioSocketAcceptor; Public classMain {Private Static Final intPORT = 8080;  Public Static voidMain (string[] args)throwsException {//instances of the service sideNiosocketacceptor accept=Newniosocketacceptor ();//add Filter,codec to serialization mode. This is the object serialization method, which means that the object is passed. Accept.getfilterchain (). AddLast ("codec", NewProtocolcodecfilter (Newobjectserializationcodecfactory ())); //add filter, log informationAccept.getfilterchain (). AddLast ("Logging",NewLoggingfilter ()); //set the handler on the server sideAccept.sethandler (NewFileuploadhandler ()); //Binding IPAccept.bind (Newinetsocketaddress (PORT)); System.out.println ("Upload server started."); }}

Handler on the server side.

ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;ImportOrg.apache.mina.core.service.IoHandlerAdapter;Importorg.apache.mina.core.session.IoSession; Public classFileuploadhandlerextendsIohandleradapter {PrivateBufferedoutputstream out;Private intcount;PrivateString fileName = "D:/log/test.jpg"; Private Static FinalLog log = Logfactory.getlog (Fileuploadhandler.class);  Public voidSessionopened (iosession session)throwsException {System.out.println ("Server Open"); }  Public voidExceptioncaught (iosession session, Throwable Cause)throwsException {System.out.println ("Exception"); Session.close (true); Super. Exceptioncaught (session, cause);}  Public voidMessagereceived (iosession session, Object message) {System.out.println ("Server Received"); Try { if(Messageinstanceoffileuploadrequest) {                 //Fileuploadrequest is used in the pass-through process. Fileuploadrequest request =(fileuploadrequest) message; System.out.println (Request.getfilename ()); if(out = =NULL) { //Create a new file input object Bufferedoutputstream, and define the location of the new file arbitrarily .out =NewBufferedoutputstream (NewFileOutputStream ("d:/log/" +request.getfilename ())); Out.write (Request.getfilecontent ()); } Else{out.write (request.getfilecontent ());} Count+=request.getfilecontent (). length;} Else if(MessageinstanceofString) { if((String) message). Equals ("Finish") {System.out.println ("Size is" +count); //here is the file transfer after the file is to be flush and close otherwise the files passed are incomplete. Out.flush (); Out.close ();//Receipt Client information, upload file successfulSession.write ("Success"); } } } Catch(Exception e) {e.printstacktrace ();}}  Public voidSessionclosed (iosession session)throwsException {System.out.println ("Server Session Close"); }}
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 for transmission.
Importjava.io.Serializable; Public classFileuploadrequestImplementsSerializable {PrivateString hostname;PrivateString filename;Private byte[] filecontent; PublicString gethostname () {returnhostname;}  Public voidsethostname (String hostname) { This. hostname =hostname;}  PublicString GetFileName () {returnfilename;}  Public voidsetfilename (String filename) { This. FileName =filename;}  Public byte[] getfilecontent () {returnfilecontent;}  Public voidSetfilecontent (byte[] filecontent) {  This. filecontent =filecontent;}}

Next look at the implementation of the client, it is also very simple:

ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;Importjava.net.InetSocketAddress;Importnio.upload.server.FileUploadRequest;Importorg.apache.mina.core.future.ConnectFuture;Importorg.apache.mina.core.session.IoSession;ImportOrg.apache.mina.filter.codec.ProtocolCodecFilter;Importorg.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;ImportOrg.apache.mina.filter.logging.LoggingFilter;ImportOrg.apache.mina.transport.socket.nio.NioSocketConnector; Public classmainclient {Private Static Final intPORT = 8080; /**  * @paramargs *@throwsIOException*/  Public Static voidMain (string[] args)throwsException {//implementation of the clientNiosocketconnector connector =Newniosocketconnector (); Connector.getfilterchain (). AddLast ("Codec", NewProtocolcodecfilter (Newobjectserializationcodecfactory ())); Connector.getfilterchain (). AddLast ("Logging",NewLoggingfilter ()); Fileuploadclienthandler h=NewFileuploadclienthandler (); Connector.sethandler (h);//this sentence needs to be added, otherwise you cannot call the following readfuture to read the information returned from the session to the server. Connector.getsessionconfig (). Setusereadoperation (true); Connectfuture CF= Connector.connect (NewInetsocketaddress ("localhost", PORT)); Iosession session; //wait for the connection to succeedcf.awaituninterruptibly (); session=cf.getsession (); System.out.println ("Client Send Begin"); //Transfer file StartString fileName = "Test.jpg"; FileInputStream FIS=NewFileInputStream (NewFile (fileName)); byte[] A =New byte[1024 * 4]; Fileuploadrequest Request=Newfileuploadrequest (); Request.setfilename (fileName); Request.sethostname ("LocalHost");  while(Fis.read (A, 0, a.length)! =-1) {request.setfilecontent (a);//write information like a session for the server to getSession.write (request);} //flag to send completeSession.write (NewString ("Finish")); System.out.println ("Client send finished and wait success"); //Access The information on the server.Object result =Session.read (). awaituninterruptibly (). GetMessage ();if(Result.equals ("Success") {System.out.println ("Success!"); //shutting down the clientconnector.dispose ();} }}

The implementation of the client handler.

ImportOrg.apache.mina.core.service.IoHandlerAdapter;Importorg.apache.mina.core.session.IoSession; Public classFileuploadclienthandlerextendsIohandleradapter { Public voidSessionopened (iosession session)throwsException {System.out.println ("Client Open"); }  Public voidSessionclosed (iosession session)throwsException {System.out.println ("Client Session Close"); }  Public voidMessagereceived (iosession session, Object message)throwsException {System.out.println ("THR result is" +message); }}

Reproduced in original

java-Communication Stocket Plugin Mina instance

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.