首先声明: MINA框架收发都使用bytebuffer;
客户端代码:
public class SocketCli {
public static void main(String[] arg) {
try {
SocketChannel mSocketChannel = SocketChannel
.open(new InetSocketAddress("192.168.1.30", 8080));
if (mSocketChannel != null) {
mSocketChannel.socket().setTcpNoDelay(false);
mSocketChannel.socket().setKeepAlive(true);
mSocketChannel.socket().setSoTimeout(60 * 1000);
mSocketChannel.configureBlocking(false);
Selector mSelector = Selector.open();
if (mSelector != null) {
mSocketChannel.register(mSelector, SelectionKey.OP_READ);
}
//用SocketChannel只能write bytebuffer类型
JsonUtls ju = new JsonUtls();
String data = ju.setHeartJsonData();
ByteBuffer bytebuffer = ByteBuffer.wrap(data.getBytes("UTF-8"));
mSocketChannel.write(bytebuffer);
bytebuffer.flip();
bytebuffer.clear();
while (mSelector.select() > 0) {
System.out.println("SocketInputStream select > 0");
Iterator<SelectionKey> iterator = mSelector.selectedKeys()
.iterator();
while (iterator.hasNext()) {
System.out.println("SocketInputStream hasNext > 0");
SelectionKey selectionkey = iterator.next();
if (selectionkey.isReadable()) {
SocketChannel socketChannel = (SocketChannel) selectionkey
.channel();
//从服务器端读到的是bytebuffer
ByteBuffer bytebuffer1 = ByteBuffer.allocate(1024);
socketChannel.read(bytebuffer1);
bytebuffer.flip();
String resultStr = new String(bytebuffer1.array(),
"UTF-8");
System.out.println("返回值>>>>>>>" + resultStr);
bytebuffer.clear();
bytebuffer = null;
// 为下一次读取做准备
selectionkey.interestOps(SelectionKey.OP_READ);
iterator.remove();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
服务器端代码:
public class MinaServer {
public static void main(String[] args) {
IoAcceptor acceptor = new NioSocketAcceptor();
acceptor.getSessionConfig().setReadBufferSize(2048);// 缓存大小
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);// 若10秒无操作进入空闲状态
//不用编码,一切收发都用bytebuffer
// acceptor.getFilterChain().addLast(
// "codec",
// new ProtocolCodecFilter(new TextLineCodecFactory(
// CharsetUtil.UTF_8)));
// acceptor.getFilterChain().addLast("codec",
// new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
acceptor.setHandler(new IoHandlerAdapter() {
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
session.close(true);
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
System.out.println("messageReceived start");
//接收到的是bytebuffer
IoBuffer bufferRe = (IoBuffer) message;
String resultStr = new String(bufferRe.array(), "UTF-8");
System.out.println(resultStr.toString());
//向客户端响应
IoBuffer buffer = IoBuffer.wrap("Hello,i'm server"
.getBytes("UTF-8"));
session.write(buffer);
}
@Override
public void messageSent(IoSession session, Object message)
throws Exception {
System.out.println("messageSent start");
}
});
try {
acceptor.bind(new InetSocketAddress("192.168.1.30", 8080));
} catch (IOException e) {
e.printStackTrace();
}
}
}
已经过测试,完全可用