java mina的使用

来源:互联网 发布:网络延迟怎么解决 编辑:程序博客网 时间:2024/06/05 14:28

这是mina需要的jar包

    // 创建一个非阻塞的Server端socket,用NIO    IoAcceptor acceptor = new NioSocketAcceptor();    // 创建接受数据的过滤器, 处理最简单的字符串传输,Mina 已经为我们提供了TextLineCodecFactory    // 编解码器工厂来对字符串进行编解码处理。    acceptor.getFilterChain().addLast("logger", new LoggingFilter());    // 设定这个过滤器将一行一行的读取数据        acceptor.getFilterChain().addLast("codec",                new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset.forName("UTF-8"))));            // 然后我们把这个IoHandler 注册到IoService:            acceptor.setHandler(new TimeServerHandler());            // 设置读取数据的缓冲区大小            acceptor.getSessionConfig().setReadBufferSize(2048);            // 设置10没有消息就进入限制状态            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);            // 绑定端口号            acceptor.bind(new InetSocketAddress(PORT));

我们可以使用自己的解码工厂

public class SocketCodecFactory implements ProtocolCodecFactory {    private final SocketDecode decoder;    private final SocketEncode encoder;    public SocketCodecFactory() {        decoder = new SocketDecode();        encoder = new SocketEncode();    }    @Override    public ProtocolDecoder getDecoder(IoSession session) throws Exception {        return decoder;    }    @Override    public ProtocolEncoder getEncoder(IoSession session) throws Exception {        return encoder;    }}
public class SocketDecode implements ProtocolDecoder {    @Override    public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {        Room room = new Room();        // protobuf序列化        // FirstProtobuf.testBuf.Builder builder =        // FirstProtobuf.testBuf.newBuilder();        // builder.setID(777);        // builder.setUrl("shiqi");        // FirstProtobuf.testBuf info = builder.build();        // 转为数组可以传递        // byte[] result = info.toByteArray();        // 这里讲result传给客户端        // protobuf反序列化得到数据        UtilsProtobuf.roomBuf buf = UtilsProtobuf.roomBuf.parseFrom(in.array());        PlayerProtobuf.roomBuf playerBuf = PlayerProtobuf.roomBuf.parseFrom(in.array());        String bufid = buf.getID() + "";        // 创建房间        if (bufid.equals("1")) {            room.oncreate();            session.write(in.array());        }        // 玩家进入房间        if (bufid.equals("2")) {            room.enter(new Player(playerBuf.getID(), playerBuf.getName(), playerBuf.getHeadUrl(), playerBuf.getGender(),                    playerBuf.getScore(), playerBuf.getReadly()));            session.write(in.array());        }        // 玩家准备或取消准备        if (bufid.equals("3")) {            room.getPlayerState(new Player(playerBuf.getID(), playerBuf.getName(), playerBuf.getHeadUrl(),                    playerBuf.getGender(), playerBuf.getScore(), playerBuf.getReadly()));            session.write(in.array());        }        if (bufid.equals("4")) {            room.begin();            session.write(in.array());        }    }    @Override    public void dispose(IoSession session) throws Exception {        // TODO Auto-generated method stub    }    @Override    public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception {        // TODO Auto-generated method stub    }}

decode中得到客户端传来的消息然后进行处理 ,此处使用了protobuf传递数据
然后是回复消息了

public class SocketEncode implements ProtocolEncoder {    @Override    public void dispose(IoSession arg0) throws Exception {        // TODO Auto-generated method stub    }    @Override    public void encode(IoSession arg0, Object arg1, ProtocolEncoderOutput out) throws Exception {        out.write(arg1);    }}
out.write(arg1); 是服务端向客户端返回数据

通讯的操作都通过IoSession来进行操作,mina封装了方法

public class TimeServerHandler implements IoHandler {    @Override    public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception {        arg1.printStackTrace();    }    @SuppressWarnings("deprecation")    @Override    public void messageReceived(IoSession session, Object message) throws Exception {        String str = message.toString();        if (str.trim().equalsIgnoreCase("quit")) {            session.close(true);            return;        }        Date date = new Date();        session.write(date.toString());        System.out.println("Message written...");    }    @Override    public void messageSent(IoSession arg0, Object arg1) throws Exception {        // TODO Auto-generated method stub        System.out.println("发送信息:" + arg1.toString());    }    @Override    public void sessionClosed(IoSession session) throws Exception {        // TODO Auto-generated method stub        System.out.println("IP:" + session.getRemoteAddress().toString() + "断开连接");    }    // 当一个新的客户端链接之后触发此方法    @Override    public void sessionCreated(IoSession session) throws Exception {        // TODO Auto-generated method stub        System.out.println("IP:" + session.getRemoteAddress().toString());    }    // 当连接空闲时触发此方法.    @Override    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {        // TODO Auto-generated method stub        System.out.println("IDLE " + session.getIdleCount(status));    }    @Override    public void sessionOpened(IoSession arg0) throws Exception {        // TODO Auto-generated method stub    }    @Override    public void inputClosed(IoSession arg0) throws Exception {        // TODO Auto-generated method stub    }}
这样就简单的完成了mina服务端的使用
0 0