编程语言 php java

mina实现服务器与客户端传送对象或字符串

java HTML我帮您 1年前  0次浏览
NIO是Java New IO的简称,在JDK1.4版本中引入该API,从那时起,就被广泛的应用。通过使用她,可以通过非阻塞的方式进行IO操作。
具体当你需要比较多的并发,而且并发的需要做长连接时,传统的连续池可能会满足不了你的需求,必竟如果连接池维护过多的连接 时,对于虚拟机的要求比较高,但如果过少连接的话,阻塞的线程会让程序处理的非常慢,这时,你就可以考虑一下使用NIO框架MINA。
服务端代码:
package cn.mina;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
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;

/**
* @author html580
* @site http://www.html580.com
*/
public class MainServer {
// 设置端口
public static int PORT = 8991;

/**
* @param args
* @throws IOException
* @author html580
*/
public static void main(String<> args) throws IOException {
System.out.println("服务创建中");
// 创建一个非阻塞的的server端socket,用NIO
SocketAcceptor acceptor = new NioSocketAcceptor();

// 创建接收数据的过滤器
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();

/*
* 这里注意点: 1:TextLineCodecFactory设置这个过滤器一行一行(/r/n)的读取数据
* 2.ObjectSerializationCodecFactory一般接收的是对象等形象,以对象形式读取
*/
// chain.addLast("chain", new ProtocolCodecFilter(new
// TextLineCodecFactory()));
chain.addLast("chain", new ProtocolCodecFilter(
new ObjectSerializationCodecFactory()));
// 设定服务器端消息处理器.:就是我们创建的TimeServerHandler对象
acceptor.setHandler(new MinaServerHandler());

acceptor.bind(new InetSocketAddress(PORT));

System.out.println("MINS 服务器监听的服务端口为" + PORT);

}

}
类似于客户端,用于处理客户端请求的类为MinaServerHandler
package cn.mina;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
* @author html580
* @site http://www.html580.com
*/
public class MinaServerHandler extends IoHandlerAdapter {
/****
* session打开时,调用
*/
@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("服务端sessionOpened..." + session.getRemoteAddress());

}

/***
* 连接关才时调用
*/
@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("服务端sessionClosed...........");
}

/**
* 如果出异常,就关闭session
*/
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
session.close(true);
}

/**
* 收到客户端信息时调用
*/
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
System.out.println("服务端收信息...");
Message msg = (Message) message;
System.out.println("服务端->收到客户机发来的消息: " + msg.getMsgBody());
msg.setMsgBody("服务端回应客户机发来的消息" + msg.getMsgBody());
session.write(msg);
System.out.println("服务端回写信息...");
}

/***
* 空闲时调用
*/
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("服务端 sessionIdle " + session.getIdleCount(status));
}
}
客户端代码
package cn.mina;

import java.io.IOException;
import java.net.InetSocketAddress;

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;
/**
* @author html580
* @site http://www.html580.com
*/
public class MinaClient {

private static int PORT = 8991;

/**
* @param args
* @throws IOException
*/
public static void main(String<> args) throws IOException {
System.out.println("开始接服务器");
// 创建TCP/IP的连接
NioSocketConnector connector = new NioSocketConnector();
// 创建接收数据的过滤器
DefaultIoFilterChainBuilder chain = connector.getFilterChain();
/*
* 这里注意点:
* 1:TextLineCodecFactory设置这个过滤器一行一行(/r/n)的发送/读取数据
* 2.ObjectSerializationCodecFactory一般发送/接收的是对象等形象,以对象形式读取
*/
//chain.addLast("myChain",new ProtocolCodecFilter(new TextLineCodecFactory()));
chain.addLast("myChain", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
Message msg = new Message("TObject");
// 设置处理的类
connector.setHandler(new MinaClientHandler(msg));
// 设置时间
connector.setConnectTimeoutMillis(300000);
// 开始连接服务器
ConnectFuture cf = connector.connect(new InetSocketAddress("localhost",PORT));
// 等待连接结束
cf.awaitUninterruptibly();
cf.getSession().getCloseFuture().awaitUninterruptibly();
connector.dispose();
}

}
客户端用MinaClientHandler来处理发送的信息,MinaClientHandler类必须继承IoHandlerAdapter,类似于Struts中处理action的类必须继承Action
package cn.mina;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
/**
* @author html580
* @site http://www.html580.com
*/
public class MinaClientHandler extends IoHandlerAdapter {

public MinaClientHandler() {
}

private Object msg;

public MinaClientHandler(Object message) {
this.msg = message;
}


@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("客户端->sessionOpened");
System.out.println("客户端->" + ((Message) msg).getMsgBody());
session.write(msg);
}

@Override
public void sessionClosed(IoSession arg0) throws Exception {
System.out.println("客户端->sessionClosed");
}

@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
Message msg = (Message) message;
System.out.println("处理完的结果为" + msg.getMsgBody());
}

@Override
public void messageSent(IoSession session, Object message) throws Exception {
// session.write(strC);
// super.messageSent(session, message);
}

@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
session.close(true);
}

}
传送对象类:
package cn.mina;

import java.io.Serializable;
/**
* @author html580
* @site http://www.html580.com
*/
public class Message implements Serializable{
private static final long serialVersionUID = 1L;
private String msgBody;

public Message(String msgBody) {
this.msgBody = msgBody;
}

public String getMsgBody() {
return msgBody;
}

public void setMsgBody(String msgBody) {
this.msgBody = msgBody;
}
}
测试结果如下:
启动服务端:
服务创建中
MINS 服务器监听的服务端口为8991
启动客户端:
开始接服务器
客户端->sessionOpened
客户端->http://www.html580.com
处理完的结果为服务端回应客户机发来的消息http://www.html580.com
服务端一直监控输出:
服务端sessionOpened.../127.0.0.1:61837
服务端收信息...
服务端->收到客户机发来的消息: http://www.html580.com
服务端回写信息...





发表评论