服务器端启动代码:
客户端连接代码:
客户端和服务器端的处理器都是继承自IoHandlerAdapter类所以只列出服务器端
以下为Mina运行所需最少的jar包
//创建一个非阻塞的Server端的Socket,用NIO
SocketAcceptor acceptor = new NioSocketAcceptor();
//创建数据过滤器
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
//设定这个过滤器将 一行一行 的读取数据
chain.addLast("myChain", new ProtocolCodecFilter(new TextLineCodecFactory()));
//设定服务器端的消息处理器
acceptor.setHandler(new SamplMainServerHandle());
//服务器端 端口
int bindPort = 9988;
//绑定端口,启动服务器
acceptor.bind(new InetSocketAddress(bindPort));
System.out.println("Mina Server is Listing on:= " + bindPort);
客户端连接代码:
//Create TCP/IP connector
NioSocketConnector client = new NioSocketConnector();
//创建接受数据的过滤器
DefaultIoFilterChainBuilder chain = client.getFilterChain();
//设定这个过滤器将一行一行(/r/n)的读取数据
chain.addLast("myChin", new ProtocolCodecFilter(new TextLineCodecFactory()));
//设置客户端的消息处理器
client.setHandler(new SamplMianClientHandle());
//set connect timeout
client.setConnectTimeoutMillis(30000);
//连接服务器
ConnectFuture cf = client.connect(new InetSocketAddress("localhost",9988));
// Wait for the connection attempt to be finished.
cf.awaitUninterruptibly();
cf.getSession().getCloseFuture().awaitUninterruptibly();
client.dispose();
客户端和服务器端的处理器都是继承自IoHandlerAdapter类所以只列出服务器端
public class SamplMainServerHandle extends IoHandlerAdapter{
private Set<IoSession> sessions = new HashSet<IoSession>();
//当一个客户端发送的消息到达时
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
//我们已设定了服务器解析消息的规则是一行一行的读取,这里可以转成String
String msg = message.toString();
// Write the received data back to remote peer
//System.out.println("收到客户端来的消息:"+msg);
//将消息回送给客户端
//session.write(msg);
for(IoSession s : sessions){
s.write(msg);
}
}
//当一个客户端连接关闭时
@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("one client Disconnet!");
}
//当一个客户端连接进入时
@Override
public void sessionOpened(IoSession session) throws Exception {
sessions.add(session);
System.out.println("incomming client:"+session.getRemoteAddress());
}
}
以下为Mina运行所需最少的jar包