基于mina框架的语音聊天服务器

来源:互联网 发布:node.js microservice 编辑:程序博客网 时间:2024/05/16 03:04

源码讲解:

        服务器源码讲解  
                    public class minaServer {
private static final int port = 10101;  
private Logger log;
TimeHandler han;
IoAcceptor ioa;
public minaServer() {
}
public void diaoyong() {
ioa = new NioSocketAcceptor();
ioa.getFilterChain().addLast("codec",
  new ProtocolCodecFilter(new proteo()));   
ioa.getSessionConfig().setReadBufferSize(1024);
han = new TimeHandler();
ioa.setHandler(han);
ioa.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
try {
 ioa.bind(new InetSocketAddress(port));
} catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}
}
public static void main(String[] args) {
minaServer mina=new minaServer();
mina.diaoyong();
}
    这段服务器代码没什么 只是自己定义了  编码过滤器 而已

先看看我们自己定义的编码器

      public class proteo implements ProtocolCodecFactory {
public ProtocolDecoder getDecoder(IoSession arg0) throws Exception {
// TODO Auto-generated method stub
return new Prototel();   这里指定了解码器的类
}
public ProtocolEncoder getEncoder(IoSession arg0) throws Exception {
// TODO Auto-generated method stub
return new encode();   这里指定了编码器的类
}
}

   编码器的类

            public class encode implements ProtocolEncoder{
 private Charset charset=Charset.forName("UTF-8");
public void dispose(IoSession arg0) throws Exception {
// TODO Auto-generated method stub

}
public void encode(IoSession arg0, Object message, ProtocolEncoderOutput arg2)
 throws Exception {
// TODO Auto-generated method stub
  IoBuffer buf=IoBuffer.allocate(100).setAutoExpand(true);
  CharsetEncoder ce=charset.newEncoder();
  buf.put((byte[])message);
  buf.put((byte)'\b');
  buf.put((byte)'\n');
  buf.flip();
  System.out.println(buf.limit());
  arg2.write(buf);
}
}
哈哈 编码器简单不    这里主要是把文件转换成byte数组类型 也就是2进制类型

解码器类

       public class Prototel implements ProtocolDecoder{
  private Charset charset=Charset.forName("UTF-8");
 // private List<IoBuffer> li=new ArrayList<IoBuffer>();
  IoBuffer buf=IoBuffer.allocate(100).setAutoExpand(true);
  public void decode(IoSession arg0, IoBuffer arg1, ProtocolDecoderOutput arg2)
 throws Exception{
buf.put(arg1);
if(arg1.get(arg1.limit()-2)=='\b' && arg1.get(arg1.limit()-1)=='\n'){
 System.out.println("这里是小数点"+buf.limit());
 buf.flip();
 arg2.write(buf);
}
}
public void dispose(IoSession arg0) throws Exception {
// TODO Auto-generated method stub

}
public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1)
 throws Exception {
// TODO Auto-generated method stub
}

}
我们用\b \n字符 去区分文件的分段保证文件的完整性


Handler类里面比较简单了

 public void messageReceived(IoSession session, Object message)
 throws Exception {
                session.write(message);       
}
以上就是语音聊天服务器的核心代码啦 简单不  我自己试着传了一个8M大小的音频文件,成功啦

而且是可以播放的哦!

原创粉丝点击