Simple implementation of Mina custom protocol and mina custom protocol

Source: Internet
Author: User

Simple implementation of Mina custom protocol and mina custom protocol

Because the company needs to create an automatic weighing system for electronic scales and implement a custom protocol, Mina is used for simple implementation. Because it is relatively simple, code is directly used. Change to Netty if you have time

Server
Package net. heartma. server; import java. io. IOException; import java.net. inetSocketAddress; import java. util. concurrent. executor; import java. util. concurrent. executors; import java. util. logging. logger; import net. heartma. protocol. customProtocolCodecFactory; import org. apache. mina. core. filterchain. defaultIoFilterChainBuilder; import org. apache. mina. core. session. idleStatus; import org. apache. mina. filter. codec. ProtocolCodecFilter; import org.apache.mina.filter.exe cutor. executorFilter; import org. apache. mina. filter. logging. loggingFilter; import org. apache. mina. transport. socket. socketAcceptor; import org. apache. mina. transport. socket. socketSessionConfig; import org. apache. mina. transport. socket. nio. nioSocketAcceptor;/*** server * @ author heartma **/public class BalanceServer {private static SocketAcceptor accept Or; private static DefaultIoFilterChainBuilder filter; private static SocketSessionConfig config; public static Logger logger = Logger. getLogger ("BalanceServer"); private static Executor threadPool = Executors. newFixedThreadPool (20); public static void main (String [] args) {// 1. Create a server-side listener acceptor = new NioSocketAcceptor (); // 2. Add LOG filter and encoding filter = acceptor. getFilterChain (); filter. addLast ("thread Pool ", new ExecutorFilter (threadPool); filter. addLast ("logger", new LoggingFilter (); // ---- encoding Filtering: converts binary or protocol-related data into an object. The TextLine factory class can process text-based information filters. addLast ("codec", new ProtocolCodecFilter (new CustomProtocolCodecFactory (); // 3. Bind the handler to the acceptor. setHandler (new BalanceServerHandler (); // 4. Set the socket property // obtain the socket connection parameter config = acceptor. getSessionConfig (); // set the buffer size of the socket to 2 MB config. setReadBufferSize (2048);/*** @ params IdleStatus arg0: Status (READ_IDLE or WRITE_IDLE) that should be concerned before it becomes the idle status * @ params IdleSt Atus arg1: the time required to change to the IDLE state (time-out period) ** if the session duration of idle is equal to that of arg1, the sessionIdle method in handler will be triggered * // set the idle state duration: 1. Here, you can set the idle state duration to read only, only set the idle waiting time for writing, or set the idle waiting time for both. The next time is the interval between two triggering of the sessionIdel method in handler. Config. setIdleTime (IdleStatus. BOTH_IDLE, 10); try {// bind the port acceptor to the server socket. bind (new InetSocketAddress (8081); logger.info ("the service has been started ...... ");} catch (IOException e) {logger.info (" Service Startup exception: "); e. printStackTrace ();}}}
Server Handler
Package net. heartma. server; import net. heartma. pojo. message; import org. apache. mina. core. service. ioHandlerAdapter; import org. apache. mina. core. session. idleStatus; import org. apache. mina. core. session. ioSession;/*** server Handler * @ author heartma **/public class BalanceServerHandler extends IoHandlerAdapter {@ Override public void exceptionCaught (IoSession ioSession, Throwable e) throws Exception {System. out. println ("exceptionCaught");} @ Override public void messageReceived (IoSession ioSession, Object obj) throws Exception {System. out. println ("messageReceived"); Message message = (Message) obj; System. out. println ("message received by the server:" + message) ;}@ Override public void messageSent (IoSession ioSession, Object obj) throws Exception {System. out. println ("messageSent") ;}@ Override public void sessionClosed (IoSession ioSession) throws Exception {System. out. println ("sessionClosed") ;}@ Override public void sessionCreated (IoSession ioSession) throws Exception {System. out. println ("sessionCreated") ;}@ Override public void sessionIdle (IoSession ioSession, IdleStatus arg1) throws Exception {System. out. println ("sessionIdle") ;}@ Override public void sessionOpened (IoSession ioSession) throws Exception {System. out. println ("sessionOpened ");}}
Client

23230e363932383834363630333738370d3030302e3434 is a Defined Protocol packet.

 

Package net. heartma. client; import java.net. inetSocketAddress; import java.net. socketAddress; import net. heartma. protocol. customProtocolCodecFactory; 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. logging. loggingFilter; import org. apache. mina. transport. socket. nio. nioSocketConnector;/*** Mina client * @ author Administrator **/public class BalanceClient {public static void main (String [] args) {// create a client connector Based on tcp/ipNioSocketConnector ctor = new NioSocketConnector (); // connection address and port SocketAddress address = new InetSocketAddress ("localhost", 8081 ); // obtain the filter chain DefaultIoFilterChainBuilder chain = connector. getFilterChain (); // configure the LOG filter and custom decoder chain. addLast ("logger", new LoggingFilter (); chain. addLast ("mycodec", new ProtocolCodecFilter (new CustomProtocolCodecFactory (); // Add the processor connector. setHandler (new BalanceClientHandler (); // connect to the server ConnectFuture future = connector ctor. connect (address); // wait until the connection is created. awaitUninterruptibly (); // send a message to the server future after the session is created. getSession (). write ("23230e363932383834363630333738370d3030302e3434"); // wait 28000 milliseconds before connecting to disconnect future. getSession (). getCloseFuture (). awaitUninterruptibly (28000); // close the connection to ctor. dispose ();}}

 

Client Handler
Package net. heartma. client; import org. apache. mina. core. service. ioHandlerAdapter; import org. apache. mina. core. session. idleStatus; import org. apache. mina. core. session. ioSession;/*** client Handler * @ author heartma **/public class BalanceClientHandler extends IoHandlerAdapter {public void exceptionCaught (IoSession ioSession, Throwable e) throws Exception {System. out. println ("exceptionCaught");} public void messageReceived (IoSession ioSession, Object obj) throws Exception {System. out. println ("messageReceived");} public void messageSent (IoSession ioSession, Object obj) throws Exception {System. out. println ("the client sends a message... "); // super. messageSent (ioSession, obj);} public void sessionClosed (IoSession ioSession) throws Exception {System. out. println ("sessionClosed");} public void sessionCreated (IoSession ioSession) throws Exception {System. out. println ("sessionCreated");} public void sessionIdle (IoSession ioSession, IdleStatus idle) throws Exception {System. out. println ("sessionIdle");} public void sessionOpened (IoSession ioSession) throws Exception {System. out. println ("sessionOpened ");}}
Entity Message body Message
Package net. heartma. pojo; import java. nio. byteBuffer; import java. nio. charBuffer; import java. nio. charset. charset;/*** defines the Message body attribute * @ author heartma **/public class Message {private String header; // the header private int length; // The length of the card number private String card; // card number private double weight; // weight public String getHeader () {return header;} public void setHeader (String header) {this. header = header;} public int getLength () {return length;} public void setLength (int length) {this. length = length;} public String getCard () {return card;} public void setCard (String card) {this. card = card;} public double getWeight () {return weight;} public void setWeight (double weight) {this. weight = weight;}/*** parse byte array * @ param messageBytes */public final boolean ReadFromBytes (byte [] messageBytes) {// obtain the header byte [] head = new byte [2]; System. arraycopy (messageBytes, 0, head,); setHeader (new String (head); // obtain the length of byte [] len = new byte [1]; System. arraycopy (messageBytes, 2, len,); setLength (len [0]); // determines whether the length of the card number is 0. If it is 0, it indicates the heartbeat information, otherwise, if (int) len [0]> 0) {// The card number parses byte [] cardDest = new byte [len [0]; System. arraycopy (messageBytes, 3, cardDest, 0, len [0]); setCard (new String (cardDest); byte [] weightDest = new byte [7]; System. arraycopy (messageBytes, 3 + length, weightDest, 0, 7); setWeight (Double. parseDouble (new String (weightDest); return true;} return false;} @ Override public String toString () {return "Message [header =" + header + ", length = "+ length +", card = "+ card +", weight = "+ weight +"] ";}}
Custom protocol Factory
Package net. heartma. protocol; import java. nio. charset. charset; import org. apache. mina. core. session. ioSession; import org. apache. mina. filter. codec. protocolCodecFactory; import org. apache. mina. filter. codec. protocolDecoder; import org. apache. mina. filter. codec. protocolEncoder;/*** custom protocol factory class * @ author heartma */public class implements ProtocolCodecFactory {private final implements decoder; private final implements encoder; public CustomProtocolCodecFactory () {this. decoder = new CustomProtocolDecoder (Charset. forName ("UTF-8"); this. encoder = new CustomProtocolEncoder (Charset. forName ("UTF-8") ;}@ Override public ProtocolDecoder getDecoder (IoSession ioSession) throws Exception {return decoder ;}@ Override public ProtocolEncoder getEncoder (IoSession ioSession) throws Exception {return encoder ;}}
Custom protocol Encoding
Package net. heartma. protocol; import java. nio. charset. charset; import net. heartma. tools. byteUtil; import org. apache. mina. core. buffer. ioBuffer; import org. apache. mina. core. session. ioSession; import org. apache. mina. filter. codec. protocolEncoderAdapter; import org. apache. mina. filter. codec. protocolEncoderOutput;/*** custom protocol encoding * @ author heartma */public class CustomProtocolEncoder extends ProtocolEncoderAdapter {private Charset charset; public CustomProtocolEncoder (Charset charset) {this. charset = charset;} @ Override public void encode (IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {byte [] hexStrToByte = ByteUtil. hexStr2ByteArray (message. toString (); IoBuffer buf = IoBuffer. allocate (hexStrToByte. length ). setAutoExpand (false); // byte [] content = Tools. hexString2Bytes (message. toString (); buf. put (hexStrToByte); buf. flip (); out. write (buf); out. flush (); buf. free ();}}
Custom protocol decoding
Package net. heartma. protocol; import java. nio. charset. charset; import java. nio. charset. charsetDecoder; import net. heartma. pojo. message; import org. apache. mina. core. buffer. ioBuffer; import org. apache. mina. core. session. ioSession; import org. apache. mina. filter. codec. protocolDecoderAdapter; import org. apache. mina. filter. codec. protocolDecoderOutput;/*** custom protocol decoding * @ author heartma */public class extends ProtocolDecoderAdapter {private CharsetDecoder decoder; public CustomProtocolDecoder (Charset charset) {this. decoder = charset. newDecoder () ;}@ Override public void decode (IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {int limit = in. limit (); byte [] bytes = new byte [limit]; in. get (bytes); Message message = new Message (); message. readFromBytes (bytes); out. write (message );}}

 

Download Code:

Http://download.csdn.net/download/cos18661062156/10141901

 

In pursuit of excellence, success will catch up with you inadvertently!

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.