apache mina 发送和接收 字节数组 byte[]

客户端:

public class ByteClient
{
  
    public static void main(String[] args) throws InterruptedException { 

        byte [] message="aaaaaaaaaaaaa".getBytes();
        try {
            MinaClient.sendMessage("127.0.0.1:8800", message);
         

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    }

MinaClient:

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class MinaClient {

static ConnectFuture cf=null;
/**
  * 创建连接
  * @param address
  * @param port
  */
static void getconnect(String address,int port){
  NioSocketConnector connector = new NioSocketConnector();
  connector.getFilterChain().addLast("logger", new LoggingFilter());
  connector.getFilterChain().addLast(
    "codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); // 设置编码过滤器
  connector.setConnectTimeout(300);
  connector.setHandler(new ClientHandler());// 设置事件处理器
  cf = connector.connect(new InetSocketAddress(address,port));// 建立连接
}
/**
  * 发送报文
  * @param serviceAddress
  * @param message
  * @throws Exception
  */
public static void sendMessage(String serviceAddress,byte[] message) throws Exception{
  String[] address = serviceAddress.split(":");
  int port =0;
  try {
   port = Integer.valueOf(address[1]);
  } catch (NumberFormatException e) {
   e.printStackTrace();
   throw new Exception("服务器地址错误!");
  }
  if(cf==null){
   getconnect(address[0],port);
  }

  cf.awaitUninterruptibly();// 等待连接创建完成
  cf.getSession().write(IoBuffer.wrap(message));// 发送消息 这里是发送字节数组的重点
  cf.getSession().getCloseFuture().awaitUninterruptibly();// 等待连接断开
}

    /**
     * 发送报文String
     * @param serviceAddress
     * @param message
     * @throws Exception
     */
    public static void sendMessage(String serviceAddress,String message) throws Exception{
        String[] address = serviceAddress.split(":");
        int port =0;
        try {
            port = Integer.valueOf(address[1]);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new Exception("服务器地址错误!");
        }
        if(cf==null){
            getconnect(address[0],port);
        }
        cf.awaitUninterruptibly();// 等待连接创建完成
        cf.getSession().write(message);// 发送消息
        cf.getSession().getCloseFuture().awaitUninterruptibly();// 等待连接断开
    }

/**
  * 回复报文
  * @param serviceAddress
  * @param message
  * @throws Exception
  */
public static void returnMessage(String serviceAddress,String message) throws Exception{
  String[] address = serviceAddress.split(":");
  int port =0;
  try {
   port = Integer.valueOf(address[1]);
  } catch (NumberFormatException e) {
   e.printStackTrace();
   throw new Exception("服务器地址错误!");
  }
  if(cf==null){
   getconnect(address[0],port);
  }
  cf.awaitUninterruptibly();// 等待连接创建完成
  cf.getSession().write(message);// 发送消息
  cf.getSession().getCloseFuture().awaitUninterruptibly();// 等待连接断开
}
}

服务端:

/**
  * 创建byte处理服务器
  * @param port端口号 time超时时间
  * @throws IOException
  */
public static void startByteService(int port,int time) throws IOException{
  // 创建服务器监听
  IoAcceptor acceptor = new NioSocketAcceptor();
  // 增加日志过滤器
  acceptor.getFilterChain().addLast("logger", new LoggingFilter());

//这里不添加字符编码过滤器
  // 指定业务逻辑处理器
  acceptor.setHandler(new byteServerHandler());
  // 设置buffer的长度
  acceptor.getSessionConfig().setReadBufferSize(2048);
  // 设置连接超时时间
  acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, time);
  // 绑定端口
  acceptor.bind(new InetSocketAddress(port));
  System.out.println("服务器在端口:"+port+"已经启动");
}

byteServerHandler:

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

/**
* 自定义的消息处理器,必须实现IoHandlerAdapter类
* @author 何明
*
*/
public class byteServerHandler extends IoHandlerAdapter{

private int count = 0;

/**
  * 当一个客户端连接进入时
  */
@Override
public void sessionOpened(IoSession session) throws Exception {

  System.out.println("incoming client: " + session.getRemoteAddress());

}

/**
  * 当一个客户端关闭时
  */
@Override
public void sessionClosed(IoSession session) throws Exception {

  System.out.println(session.getRemoteAddress() + "is Disconnection");

}

@Override
public void messageReceived(IoSession session, Object message)
   throws Exception {

       IoBuffer ioBuffer = (IoBuffer)message; 
       byte[] b = new byte[ioBuffer.limit()]; 
       ioBuffer.get(b);
   
  String msg=new String(b);

  System.out.println("收到客户端发来的消息为" + "  " + msg);
 
  //将测试消息会送给客户端
  //session.write(str + count);
}

}

运行结果:

服务器在端口:8800已经启动
incoming client: /127.0.0.1:1353
收到客户端发来的消息长度为  13
收到客户端发来的消息为  aaaaaaaaaaaaa

猜你喜欢

转载自cms163.iteye.com/blog/1964307