Reference article: http://blog.chinabyte.com/a/534099.html
Reason for passing the object: Personal understanding: In line with object-oriented, the server needs to parse, process, and respond to receive client messages. If the object is passed, the parsing, processing, and response can be written in the object. This way, the scalability is better .
client
1 MinaClient.java
package com.nafio.client; import java.net.InetSocketAddress; import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; import org.apache.mina.transport.socket.nio.NioSocketConnector; /** * @author nafio 2012-08-20 * mina pass object client */ public class MinaClient { // use singleton pattern private static MinaClient minaClient = null; //Create TCP/IP connector NioSocketConnector connector = new NioSocketConnector(); //Create a filter to receive data DefaultIoFilterChainBuilder chain = connector.getFilterChain(); // use singleton //The related IoHandlerAdapter inherited classes all adopt the single instance mode //In the whole communication process, we can achieve a single instance of the object, session, etc., to prevent the phenomenon of "trusted inhumans". //Is this not very understandable? public static MinaClient getInstances() { if (null == minaClient) { minaClient = new MinaClient(); } return minaClient; } private MinaClient() { // Setting this filter will read data by object chain.addLast("myChin", new ProtocolCodecFilter( new ObjectSerializationCodecFactory())); connector.setHandler(ClientHandler.getInstances(connector));//by nafio is used to completely close the client connection //Set the connection timeout connector.setConnectTimeout(30); //connect to the server ConnectFuture cf = connector.connect(new InetSocketAddress("localhost", 8888)); } public static void main(String args[]) { MinaClient.getInstances(); } }
2 ClientHandler.java
package com.nafio.client; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.transport.socket.nio.NioSocketConnector; import com.nafio.obj.TransferObj; /** * @author nafio 2012-08-20 * mina pass object client */ public class ClientHandler extends IoHandlerAdapter { private static ClientHandler minaClientHandler = null; NioSocketConnector connector;//by nafio is used to completely close the client connection public static ClientHandler getInstances(NioSocketConnector con) { if (null == minaClientHandler) { minaClientHandler = new ClientHandler(con); } return minaClientHandler; } private ClientHandler(NioSocketConnector con) { connector=con; } public void sessionOpened(IoSession session) throws Exception { //session.write("From the client: open a session with the server"); System.out.println("Client: Opened a session with the server"); sendMsg(session); } // Triggered after the session ends public void sessionClosed(IoSession session) { System.out.println("Client: End of session with server"); } //Triggered after receiving the return message public void messageReceived(IoSession session, Object message)throws Exception { System.out.println("Client: Received the information returned by the server"); } // Triggered when the connection is created public void sessionCreated(IoSession session) throws Exception { super.sessionCreated(session); System.out.println("Client: Create a connection with the server"); } //Connection idle is triggered public void sessionIdle(IoSession session, IdleStatus status) throws Exception { super.sessionIdle(session, status); System.out.println("Client: Connection idle"); } //Triggered after sending information public void messageSent(IoSession arg0, Object arg1) throws Exception { //System.out.println("Client: Sent to server -->"+(String)arg1); System.out.println("Client: Finished sending object"); arg0.close();//The fact that mina2.0 cannot be completely closed here requires connector.dispose() to be completely closed connector.dispose();//You don't need to close and remove these two sentences and it's ok System.out.println("Client: Forcibly close the connection"); } /** * Send information * @param session * @throws Exception */ public void sendMsg(IoSession session) throws Exception{ TransferObj transferObj=new TransferObj(); transferObj.setDate("nafio_date"); session.write(transferObj); } public void exceptionCaught(IoSession session, Throwable cause) throws Exception { super.exceptionCaught(session, cause); } }
3 TransferObj.java
package com.nafio.obj; public class TransferObj implements java.io.Serializable{ private String date; public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
Server
1 MinaServer.java
package com.nafio.server; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; import org.apache.mina.transport.socket.SocketAcceptor; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; public class MinaServer { private static MinaServer minaServer = null; //Create a non-blocking server-side Socket private SocketAcceptor acceptor = new NioSocketAcceptor(); //Create a filter to receive data private DefaultIoFilterChainBuilder chain = acceptor.getFilterChain(); private int bindPort = 8888; // singleton public static MinaServer getInstances() { if (null == minaServer) { minaServer = new MinaServer(); } return minaServer; } private MinaServer() { // Setting this filter will read data by object chain.addLast("myChin", new ProtocolCodecFilter( new ObjectSerializationCodecFactory())); //Set the message handler on the server side: a MinaServerHandler object, acceptor.setHandler(ServerHandler.getInstances()); try { //Bind the port, start the server acceptor.bind(new InetSocketAddress(bindPort)); } catch (IOException e) { e.printStackTrace (); } System.out.println("Server: listening port--->" + bindPort); } public static void main(String[] args) throws Exception { MinaServer.getInstances(); } }
2 ServerHandler.java
package com.nafio.server; import org.apache.mina.core.filterchain.IoFilterAdapter; import org.apache.mina.core.service.IoHandler; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import com.nafio.obj.TransferObj; //The following two ways of writing should be equivalent, not sure? //public class ServerHandler extends IoHandlerAdapter { public class ServerHandler extends IoFilterAdapter implements IoHandler { private static ServerHandler samplMinaServerHandler = null; public static ServerHandler getInstances() { if (null == samplMinaServerHandler) { samplMinaServerHandler = new ServerHandler(); } return samplMinaServerHandler; } private ServerHandler() { } public void sessionOpened(IoSession session) throws Exception { } public void sessionClosed(IoSession session) { } public void messageReceived(IoSession session, Object message)throws Exception { if (message instanceof TransferObj) { TransferObj obj = (TransferObj) message; System.out.println("Server: Received client data--->"+obj.getDate()); } } public void exceptionCaught(IoSession arg0, Throwable arg1)throws Exception { } public void messageSent(IoSession arg0, Object arg1) throws Exception { } public void sessionCreated(IoSession arg0) throws Exception { } public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception { } }
3 TransferObj.java (same as the client, because the client and the server are separated, so this class is placed in both projects)
How to completely close the mina client connection
session.close();
This method is deprecated by default in java
After this method is used, the client has not actually been completely closed.
mina2.0 is completely closed with connector.dispose();
About socket long and short connection
The usual short connection operation steps are:
connection→data transmission→close connection;
while long connection is usually:
connection→data transmission→keep connection (heartbeat)→data transmission→keep connection (heartbeat)→…→close connection;
this It is required that long connections send data packets (heartbeat) regularly when there is no data communication to maintain the connection state, and short connections can be closed directly when there is no data transmission.
So mina should be a long connection by default, so it is not closed by default.