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

源码讲解:

        服务器源码讲解  
                    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大小的音频文件,成功啦

而且是可以播放的哦!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值