MINA的UDP协议demo

itmale 2012-10-17

服务端代码

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.charset.Charset;

import java.util.Date;

import org.apache.log4j.Logger;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;

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.textline.LineDelimiter;

import org.apache.mina.filter.codec.textline.TextLineCodecFactory;

import org.apache.mina.filter.logging.LoggingFilter;

import org.apache.mina.transport.socket.DatagramSessionConfig;

import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;

public class ServerHandler extends IoHandlerAdapter {

    private static Logger logger = Logger.getLogger(ServerHandler.class);

    public ServerHandler() throws IOException {

        NioDatagramAcceptor acceptor = new NioDatagramAcceptor();

        acceptor.setHandler(this);

        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();

        chain.addLast("logger", new LoggingFilter());

        chain.addLast("codec", new ProtocolCodecFilter(

                new TextLineCodecFactory(Charset.forName("UTF-8"),

                        LineDelimiter.NUL, LineDelimiter.NUL)));

        DatagramSessionConfig dcfg = acceptor.getSessionConfig();

        dcfg.setReuseAddress(true);

        acceptor.bind(new InetSocketAddress(1234));

    }

    public void messageReceived(IoSession session, Object message)

            throws Exception {

        System.out.println(message.toString() + ":" + new Date());

    }

    public void exceptionCaught(IoSession session, Throwable cause)

            throws Exception {

        logger.error("MINA发生异常:", cause);

    }

    public void sessionOpened(IoSession session) throws Exception {

        super.sessionOpened(session);

    }

    public void sessionIdle(IoSession session, IdleStatus status)

            throws Exception {

        super.sessionIdle(session, status);

    }

    public static void main(String[] args) throws IOException {

        new ServerHandler();

    }

}

客户端代码

import java.net.InetSocketAddress;

import java.nio.charset.Charset;

import org.apache.log4j.Logger;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;

import org.apache.mina.core.future.ConnectFuture;

import org.apache.mina.core.future.IoFuture;

import org.apache.mina.core.future.IoFutureListener;

import org.apache.mina.core.service.IoHandlerAdapter;

import org.apache.mina.core.session.IoSession;

import org.apache.mina.filter.codec.ProtocolCodecFilter;

import org.apache.mina.filter.codec.textline.LineDelimiter;

import org.apache.mina.filter.codec.textline.TextLineCodecFactory;

import org.apache.mina.filter.logging.LoggingFilter;

import org.apache.mina.transport.socket.DatagramConnector;

import org.apache.mina.transport.socket.nio.NioDatagramConnector;

public class Client extends IoHandlerAdapter {

    private static Logger logger = Logger.getLogger(Client.class);

    DatagramConnector connector;

    IoSession session;

    public Client() {

        connector = new NioDatagramConnector();

        connector.setHandler(this);

        DefaultIoFilterChainBuilder chain = connector.getFilterChain();

        chain.addLast("logger", new LoggingFilter());

        chain.addLast("codec", new ProtocolCodecFilter(

                new TextLineCodecFactory(Charset.forName("UTF-8"),

                        LineDelimiter.NUL, LineDelimiter.NUL)));

        IoFuture connFuture = connector.connect(new InetSocketAddress(

                "127.0.0.1", 1234));

        connFuture.addListener(new IoFutureListener() {

            public void operationComplete(IoFuture future) {

                ConnectFuture connFuture = (ConnectFuture) future;

                if (connFuture.isConnected()) {

                    session = future.getSession();

                    try {

                        sendData();

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                } else {

                    logger.error("Not connected...exiting");

                }

            }

        });

    }

    private void sendData() throws InterruptedException {

        session.write("测试数据发送!");

    }

    public static void main(String[] args) {

        new Client();

    }

}

相关推荐

fengshantao / 0评论 2016-03-25

claytang / 0评论 2013-05-06