Java socket 开源框架MINA(三)
下面的这个简单的example演示client和server传递object的过程:
Message.java
public class Message implements Serializable {
private int type;
private int status;
private String msgBody;
public Message(int type, int status, String msgBody)
{
this.type = type;
this.status = status;
this.msgBody = msgBody;
}
public String getMsgBody() {
return msgBody;
}
public void setMsgBody(String msgBody) {
this.msgBody = msgBody;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
Client.java
public class Client
{
private static final String HOSTNAME = "localhost";
private static final int PORT = 8080;
private static final int CONNECT_TIMEOUT = 30; // seconds
public static void main( String[] args ) throws Throwable
{
SocketConnector connector = new SocketConnector();
// Configure the service.
SocketConnectorConfig cfg = new SocketConnectorConfig();
cfg.setConnectTimeout( CONNECT_TIMEOUT );
cfg.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter( new ObjectSerializationCodecFactory() ) );
cfg.getFilterChain().addLast( "logger", new LoggingFilter() );
IoSession session;
Message msg = new Message(0,1,"hello");
connector.connect(new InetSocketAddress( HOSTNAME, PORT ),
new ClientSessionHandler(msg), cfg );
}
}
ClientSessionHandler.java
public class ClientSessionHandler extends IoHandlerAdapter
{
private Object msg;
public ClientSessionHandler(Object msg)
{
this.msg = msg;
}
public void sessionOpened( IoSession session )
{
session.write(this.msg);
}
public void messageReceived( IoSession session, Object message )
{
System.out.println("in messageReceived!");
Message rm = (Message ) message;
SessionLog.debug(session, rm.getMsgBody());
System.out.println("message is: " + rm.getMsgBody());
session.write(rm);
}
public void exceptionCaught( IoSession session, Throwable cause )
{
session.close();
}
}
Server.java
public class Server
{
private static final int SERVER_PORT = 8080;
public static void main( String[] args ) throws Throwable
{
IoAcceptor acceptor = new SocketAcceptor();
// Prepare the service configuration.
SocketAcceptorConfig cfg = new SocketAcceptorConfig();
cfg.setReuseAddress( true );
cfg.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter( new ObjectSerializationCodecFactory() ) );
cfg.getFilterChain().addLast( "logger", new LoggingFilter() );
acceptor.bind(
new InetSocketAddress( SERVER_PORT ),
new ServerSessionHandler( ), cfg );
System.out.println( "The server Listening on port " + SERVER_PORT );
}
}
ServerSessionHandler.java
public class ServerSessionHandler extends IoHandlerAdapter
{
public void sessionOpened( IoSession session )
{
// set idle time to 60 seconds
session.setIdleTime( IdleStatus.BOTH_IDLE, 60 );
session.setAttribute("times",new Integer(0));
}
public void messageReceived( IoSession session, Object message )
{
System.out.println("in messageReceived");
int times = ((Integer)(session.getAttribute("times"))).intValue();
System.out.println("tiems = " + times);
// communicate 30 times,then close the session.
if (times < 30)
{
times++;
session.setAttribute("times", new Integer(times));
Message msg;
msg = (Message) message;
msg.setMsgBody("in server side: " + msg.getMsgBody());
System.out.println("begin send msg: " + msg.getMsgBody());
session.write(msg);
}
else
{
session.close();
}
}
public void sessionIdle( IoSession session, IdleStatus status )
{
SessionLog.info( session, "Disconnecting the idle." );
// disconnect an idle client
session.close();
}
public void exceptionCaught( IoSession session, Throwable cause )
{
// close the connection on exceptional situation
session.close();
}
}
MINA自己附带的Demo已经很好的说明了它的运用。
值得一提的是它的SumUp:客户端发送几个数字,服务端求和后并返回结果。这个简单的程序演示了如何自己实现CODEC。
补充提示:
下载并运行MINA的demo程序还颇非周折:
运行MINA demo appli擦tion:
1:在JDK5
产生错误:
Exception in thread "main" java.lang.NoClassDefFoundError: edu/emory/mathcs/backport/java/util/concurrent/Executor
at org.apache.mina.example.reverser.Main.main(Main.java:44)
察看mina的QA email:
http://www.mail-archive.com/[email protected]/msg02252.html
原来需要下载:backport-util-concurrent.jar并加入classpath
http://dcl.mathcs.emory.edu/util/backport-util-concurrent
继续运行还是报错:
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
原来MINA采用了slf4j项目作为log,继续下载
slf4j-simple.jar等,并加入classpath:
http://www.slf4j.org/download.html
附件是mina demo的eclipse工程。导入就可运行,所有的相关jar包在bin目录下
1 楼
maozilee
2011-08-22
mina开发c/s架构的程序简单多了