Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to transfer objects in Apache MINA

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

It is believed that many inexperienced people don't know what to do about how to transfer objects in Apache MINA. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Using Apache MINA to transfer objects is very easy for MINA, and it is also a common application in Java network programming. In fact, for MINA transfer objects, if you have read the previous article, you can achieve object delivery by making a few changes in it, but all the code examples are given here, considering the integrity of the example.

First, look at the two Java objects, MyRequestObject and MyResponseObject, which are used for passing. They simply implement the Serializable interface.

Package com.google.code.garbagecan.minastudy.sample3; import java.io.Serializable; public class MyRequestObject implements Serializable {private static final long serialVersionUID = 1L; private String name; private String value; public MyRequestObject (String name, String value) {this.name = name; this.value = value;} public String getName () {return name } public void setName (String name) {this.name = name;} public String getValue () {return value;} public void setValue (String value) {this.value = value;} @ Override public String toString () {StringBuffer sb = new StringBuffer () Sb.append ("Request [name:" + name + ", value:" + value + "]"); return sb.toString ();}} package com.google.code.garbagecan.minastudy.sample3; import java.io.Serializable; public class MyResponseObject implements Serializable {private static final long serialVersionUID = 1L; private String name; private String value Public MyResponseObject (String name, String value) {this.name = name; this.value = value;} public String getName () {return name;} public void setName (String name) {this.name = name;} public String getValue () {return value } public void setValue (String value) {this.value = value;} @ Override public String toString () {StringBuffer sb = new StringBuffer (); sb.append ("Response [name:" + name + ", value:" + value + "]"); return sb.toString ();}}

Look at the code on the server side

Package com.google.code.garbagecan.minastudy.sample3; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.mina.core.service.IoAcceptor; 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.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; import org.apache.mina.filter.logging.LoggingFilter Import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyServer {private static final Logger logger = LoggerFactory.getLogger (MyServer.class); public static void main (String [] args) {IoAcceptor acceptor = new NioSocketAcceptor (); acceptor.getFilterChain () .addLast ("logger", new LoggingFilter ()) Acceptor.getFilterChain () .addLast ("codec", new ProtocolCodecFilter (new ObjectSerializationCodecFactory ()) Acceptor.setHandler (new IoHandlerAdapter () {@ Override public void sessionCreated (IoSession session) throws Exception {} @ Override public void sessionOpened (IoSession session) throws Exception {} @ Override public void sessionClosed (IoSession session) throws Exception {} @ Override public void sessionIdle (IoSession session IdleStatus status) throws Exception {} @ Override public void exceptionCaught (IoSession session, Throwable cause) throws Exception {logger.error (cause.getMessage (), cause) Session.close (true);} @ Override public void messageReceived (IoSession session, Object message) throws Exception {logger.info ("Received" + message); MyRequestObject myReqOjb = (MyRequestObject) message; MyResponseObject myResObj = new MyResponseObject (myReqOjb.getName (), myReqOjb.getValue ()) Session.write (myResObj);} @ Override public void messageSent (IoSession session, Object message) throws Exception {logger.info ("Sent" + message);}}); try {acceptor.bind (new InetSocketAddress (10000)) } catch (IOException ex) {logger.error (ex.getMessage (), ex);}

1. The first step is to create the NioSocketAcceptor O Service, where the NioSocketAcceptor class is used to create an instance of IoAcceptor.

two。 To create the ObjectSerializationCodecFactory O Filter Chain, two IoFilter are used, one is LoggingFilter to log and print event messages, the other is the ProtocolCodecFilter instance to encode the data, and the ObjectSerializationCodecFactory class is used to serialize or deserialize the data into java objects.

3. To create the messageReceived O Handler, take a look at the messageReceived method, which always receives a MyRequestObject object and then sends a MyResponseObject object to the client.

4. * allows the IoAcceptor class instance to bind the port to listen.

Look at the code on the client side.

Package com.google.code.garbagecan.minastudy.sample3; import java.net.InetSocketAddress; import org.apache.mina.core.RuntimeIoException; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.service.IoConnector; 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.filter.codec.ProtocolCodecFilter Import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.transport.socket.nio.NioSocketConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyClient {private static final Logger logger = LoggerFactory.getLogger (MyClient.class); public static void main (String [] args) {IoConnector connector = new NioSocketConnector () Connector.setConnectTimeoutMillis (10 * 1000); connector.getFilterChain (). AddLast ("logger", new LoggingFilter ()); connector.getFilterChain () .addLast ("codec", new ProtocolCodecFilter (new ObjectSerializationCodecFactory () Connector.setHandler (new IoHandlerAdapter () {@ Override public void sessionCreated (IoSession session) throws Exception {} @ Override public void sessionOpened (IoSession session) throws Exception {MyRequestObject myObj = new MyRequestObject ("my name", "my value"); session.write (myObj) } @ Override public void sessionClosed (IoSession session) throws Exception {} @ Override public void sessionIdle (IoSession session, IdleStatus status) throws Exception {} @ Override public void exceptionCaught (IoSession session, Throwable cause) throws Exception {logger.error (cause.getMessage (), cause) Session.close (true);} @ Override public void messageReceived (IoSession session, Object message) throws Exception {MyResponseObject myResObj = (MyResponseObject) message; logger.info ("Received" + myResObj); session.close (true) } @ Override public void messageSent (IoSession session, Object message) throws Exception {logger.info ("Sent" + message);}}); IoSession session = null; try {ConnectFuture future = connector.connect (new InetSocketAddress ("localhost", 10000)); future.awaitUninterruptibly () Session = future.getSession ();} catch (RuntimeIoException e) {logger.error (e.getMessage (), e);} session.getCloseFuture (). AwaitUninterruptibly (); connector.dispose ();}}

1. First create the NioSocketConnector O Service, where the NioSocketConnector class is used to create an instance of IoConnector and set the connection timeout to 10 seconds.

two。 To create the IoFilter O Filter Chain, two CPUs are also set up on the server side, one is LoggingFilter to log and print event messages, the other is the ProtocolCodecFilter instance to encode the data, and the ObjectSerializationCodecFactory class is also used to serialize or deserialize the data into java objects.

3. To create the sessionOpened O Handler, take a look at the sessionOpened method, where the MyRequestObject object is sent in the session establishment event, and then the MyResponseObject object is accepted in the messageReceived method.

4. * is the Server where the IoConnector instance class connects to the remote end.

Let's test the above program, first run the MyServer class, and then run the MyClient class, and you can see the event log and the sent / received objects on their respective terminals.

After reading the above, have you mastered the method of how to transfer objects in Apache MINA? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report