import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import java.io.IOException;
import java.net.InetSocketAddress;
/**
* MINA:基于TCP/IP通信协议的简单易用的java框架,在网络通信方面非常强大
* 开发一个MINA应用三个步骤:1.创建连接 2.设定过滤规则 3.编写自己的消息处理器
*/
public class Server {
public static void main(String[] args) {
//创建一个非阻塞的server端socket NIO
SocketAcceptor acceptor = new NioSocketAcceptor();
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
//设定一个过滤器,一行一行的读取数据(/r/n)
chain.addLast("mychain", new ProtocolCodecFilter(new TextLineCodecFactory()));
//设置服务器端的消息处理器
acceptor.setHandler(new MinaServerHandler());
int port = 9000;//服务器的端口号
try {
//绑定端口,启动服务器(不会阻塞,立即返回)
acceptor.bind(new InetSocketAddress(port));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Mina Server is Running, listening on"+port);
}
}
另一个类文件
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
/**
* 服务器端的消息处理器
*/
public class MinaServerHandler extends IoHandlerAdapter {
//一次会话打开
@Override
public void sessionOpened(IoSession session) throws Exception {
super.sessionOpened(session);
System.out.println("welcome client"+session.getRemoteAddress());
}
//会话关闭
@Override
public void sessionClosed(IoSession session) throws Exception {
super.sessionClosed(session);
System.out.println("client close");
}
//接收消息
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
super.messageReceived(session, message);
String msg = (String) message;
System.out.println("收到客户端发来的消息:"+msg);
session.write("echo"+msg);
}
}