mina1.7
发布日期:2025-04-14 02:51:51 浏览次数:10 分类:精选文章

本文共 3833 字,大约阅读时间需要 12 分钟。

Mina框架 Java 服务器示例

简单的 TCP/IP 服务器实现

本文将介绍如何使用 Apache Mina 框架快速搭建一个简单的 TCP/IP 服务器。通过本文的示例,读者能够理解 Mina 的基本配置和使用方法。

服务器端代码解析

package com.allinpay.mina;import java.io.IOException;import java.net.InetSocketAddress;import org.apache.mina.common.IoAcceptor;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.transport.socket.nio.SocketAcceptor;import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;

服务器配置

private int SERVER_PORT = 10000;private IoAcceptor acceptor = null;public class MyServer {    private static int Server_Session_IdleSec = 5 * 60; // 5分钟    public MyServer(int aServerPort) throws IOException {        SERVER_PORT = aServerPort;        connect();    }    public void connect() throws IOException {        close();        acceptor = new SocketAcceptor();        SocketAcceptorConfig cfg = new SocketAcceptorConfig();        cfg.setReuseAddress(true);        cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MyCodecFactory()));        // 注:以下日志配置可根据需要添加        // cfg.getFilterChain().addLast("logger", new LoggingFilter());        acceptor.bind(new InetSocketAddress(SERVER_PORT), new MyServerIoSessionHandler(this), cfg);    }    public void close() throws IOException {        if (acceptor != null) {            acceptor.unbindAll();            acceptor = null;        }        return true;    }    public static void main(String[] args) throws IOException {        new MyServer(10000);    }}

服务器连接处理

public class MyServerIoSessionHandler extends IoHandlerAdapter {    private MyServer server;    public MyServerIoSessionHandler(MyServer channel) {        super();        this.server = channel;    }    public void sessionOpened(IoSession session) {        session.setIdleTime(IdleStatus.READER_IDLE, Server_Session_IdleSec);    }    public void messageReceived(IoSession session, Object message) {        String orderMsg = (String) message;        if (orderMsg == null) {            return;        }        session.write(orderMsg);    }    public void sessionIdle(IoSession session, IdleStatus status) throws IOException {        session.close();        server.connect();    }    public void exceptionCaught(IoSession session, Throwable cause) throws IOException {        session.close();        server.connect();    }}

数据编码/解码

public class MyCodecFactory implements ProtocolCodecFactory {    private final MyEncoder encoder;    private final MyDecoder decoder;    public MyCodecFactory() {        encoder = new MyEncoder();        decoder = new MyDecoder();    }    public MyEncoder getEncoder() {        return encoder;    }    public MyDecoder getDecoder() {        return decoder;    }}

数据编码实现

public class MyEncoder extends ProtocolEncoderAdapter {    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {        String response = (String) message;        byte[] bt = response.getBytes("GBK");        ByteBuffer buf = ByteBuffer.allocate(bt.length).setAutoExpand(true);        buf.put(bt);        buf.flip();        out.write(buf);    }}

数据解码实现

public class MyDecoder extends ProtocolDecoderAdapter {    public void decode(IoSession session, ByteBuffer buf, ProtocolDecoderOutput out) throws Exception {        byte[] b = new byte[buf.limit()];        buf.get(b);                byte[] head = new byte[64];        System.arraycopy(b, 0, head, 0, 64);        String headstring = new String(head);                int length = Integer.parseInt(headstring.substring(8, 16).trim());        byte[] body = new byte[length];        System.arraycopy(b, 64, body, 0, length);        return new String(body, "GBK");    }}

服务器运行

  • 编写上述代码到一个 Java 文件中
  • 编译运行,使用 java YourServerClass 命令启动服务器
  • 在另一个终端窗口,使用 telnet localhost 10000 连接服务器
  • 总结

    通过以上代码示例,读者可以快速了解如何使用 Apache Mina 框架搭建 TCP/IP 服务器,并通过自定义编码解码实现数据处理。Mina 提供了强大的灵活性,适合处理各种网络通信场景。

    上一篇:Mina中的协议制订和解析策略
    下一篇:Mina Basics 04- 会话

    发表评论

    最新留言

    初次前来,多多关照!
    [***.217.46.12]2025年05月08日 06时29分15秒