首页 > 代码库 > mina通信 demo
mina通信 demo
1,要用到4个jar
2,服务端
package mina.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MainServer {
private final static Logger log = LoggerFactory
.getLogger(MainServer.class);
private static MainServer mainServer = null;
private SocketAcceptor acceptor = new NioSocketAcceptor();
private DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
private int bindPort = 8888;
public static MainServer getInstances() {
if (null == mainServer) {
mainServer = new MainServer();
}
return mainServer;
}
private MainServer() {
chain.addLast("myChin", new ProtocolCodecFilter(
new ObjectSerializationCodecFactory()));
acceptor.setHandler(ServerHandler.getInstances());
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
try {
acceptor.bind(new InetSocketAddress(bindPort));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
MainServer.getInstances();
}
}
package mina.server;
import java.util.Collection;
import java.util.Date;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import mina.Object.UserInfo;
import mina.client.ClientHandler;
public class ServerHandler extends IoFilterAdapter implements IoHandler {
private final static Logger log = LoggerFactory
.getLogger(ServerHandler.class);
private static ServerHandler samplMinaServerHandler = null;
public static ServerHandler getInstances() {
if (null == samplMinaServerHandler) {
samplMinaServerHandler = new ServerHandler();
}
return samplMinaServerHandler;
}
private ServerHandler() {
}
// 当连接后打开时触发此方法,一般此方法与 sessionCreated 会被同时触发
@Override
public void sessionOpened(IoSession session) throws Exception {
session.write("welcome to the chat room !");
}
@Override
public void sessionClosed(IoSession session) {
CloseFuture closeFuture = session.close(true);
closeFuture.addListener(new IoFutureListener<IoFuture>() {
public void operationComplete(IoFuture future) {
if (future instanceof CloseFuture) {
System.out.println("sessionClosed~~~~~~~"+future);
((CloseFuture) future).setClosed();
}
}
});
}
//服务器接收到数据
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
if (message instanceof UserInfo) {
UserInfo text = (UserInfo) message;
System.out.println("服务器接收到从客户端的姓名:"+text.getName());
System.out.println("服务器接收到从客户端的QQ:"+text.getQQNum());
}else{
System.out.println(message);
}
// 拿到所有的客户端Session
Collection<IoSession> sessions = session.getService().getManagedSessions().values();
// 向所有客户端发送数据
for (IoSession sess : sessions) {
UserInfo text = (UserInfo) message;
sess.write(new Date()+":服务器已收到 "+text.getName());
}
System.out.println("客户端数量: "+sessions.size());
}
@Override
public void exceptionCaught(IoSession arg0, Throwable arg1)
throws Exception {
}
// 当消息传送到客户端后触发
@Override
public void messageSent(IoSession arg0, Object message) throws Exception {
System.out.println("当消息传送到客户端后触发 "+message );
}
// 当一个新客户端连接后触发此方法.
@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println(" 当一个新客户端连接后触发此方法. " );
//session.write("welcome to the chat room !");
}
// 当连接空闲时触发此方法.
@Override
public void sessionIdle(IoSession session, IdleStatus arg1) throws Exception {
System.out.println(" 当连接空闲时触发此方法 " );
//session.close(true);
}
}
3,客户端
package mina.client;
import java.net.InetSocketAddress;
import mina.server.MainServer;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MainClient {
private final static Logger log = LoggerFactory
.getLogger(MainServer.class);
private static MainClient mainClient = null;
NioSocketConnector connector = new NioSocketConnector();
DefaultIoFilterChainBuilder chain = connector.getFilterChain();
public static MainClient getInstances() {
if (null == mainClient) {
mainClient = new MainClient();
}
return mainClient;
}
private MainClient() {
chain.addLast("myChin", new ProtocolCodecFilter(
new ObjectSerializationCodecFactory()));//注册
connector.setHandler(ClientHandler.getInstances());//build
connector.setConnectTimeout(30);//连接超时
ConnectFuture cf = connector.connect(new InetSocketAddress("localhost",
8888));//连接
cf.awaitUninterruptibly();//等待
}
public static void main(String args[]) {
MainClient.getInstances();
}
}
package mina.client;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import mina.Object.UserInfo;
public class ClientHandler extends IoHandlerAdapter {
private final static Logger log = LoggerFactory
.getLogger(ClientHandler.class);
private static ClientHandler samplMinaClientHandler = null;
public static ClientHandler getInstances() {
if (null == samplMinaClientHandler) {
samplMinaClientHandler = new ClientHandler();
}
return samplMinaClientHandler;
}
private ClientHandler() {
}
//当连接打开是调用
@Override
public void sessionOpened(IoSession session) throws Exception {
//session.write("客户端与服务器的会话打开了……");
UserInfo text=new UserInfo();
text.setName("梅竹~~~~寒香");
text.setQQNum("972341215");
session.write(text);
}
@Override
public void sessionClosed(IoSession session) {
System.out.println("sessionClosed~~~~~~~"+session);
}
//当接收了一个消息时调用;
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
System.out.println("xxy~~~~~~~"+message);
session.write("^^^^^^^^^^^^");
}
//当一个消息被(IoSession#write)发送出去后调用;
@Override
public void messageSent(IoSession session, Object obj) throws Exception {
//session.write("GGGGGGGGGGGGGGGG");
System.out.println("客户端已经向服务器发送了:"+(String)obj+"uuuuuuuuu"+session);
}
}
4,测试
先run服务端,再run客户端
OVER!!!
mina通信 demo