`
benx
  • 浏览: 276268 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Mina Server/Client 例子

    博客分类:
  • java
阅读更多

Mina 需要mina.jar ,log4j.jar,slf4j.jar

 

Server端

package Server;

import java.net.InetSocketAddress;

import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
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;

public class MinaServer {
	
	public void init() throws Exception{
		SocketAcceptor acceptor = new NioSocketAcceptor(Runtime.getRuntime().availableProcessors() + 1);
		//设置解析器
		DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
		chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory()));
		
		acceptor.setHandler(new BexnHandler());
		acceptor.bind(new InetSocketAddress(8080));
		
	}
	public MinaServer() throws Exception {
		init();
	}
	
	public static void main(String[] args) throws Exception {
		new MinaServer();
		System.out.println("Server start");
	}
}

class BexnHandler extends IoHandlerAdapter{
	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		System.out.println("messageReceived " + message);
		super.messageReceived(session, message);
		session.write("messageReceived "+message);
		session.closeOnFlush();
	}
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		if (session.isConnected()) {
			session.close();
		}
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		session.close();
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		super.sessionClosed(session); 
		System.out.println("sessionClosed");
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30000);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		session.close();
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		super.sessionOpened(session);
	}
}


 

Client端

package Client;

import java.io.ObjectInputStream.GetField;
import java.net.ConnectException;
import java.net.InetSocketAddress;

import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.RuntimeIoException;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class MinaClient {
	public SocketConnector socketConnector;

	/**
	 * 缺省连接超时时间
	 */
	public static final int DEFAULT_CONNECT_TIMEOUT = 5;

	public static final String HOST = "localhost";

	public static final int PORT = 8080;

	public MinaClient() {
		init();
	}

	public void init() {
		socketConnector = new NioSocketConnector();

		// 长连接
		// socketConnector.getSessionConfig().setKeepAlive(true);

		socketConnector.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);

		socketConnector.setReaderIdleTime(DEFAULT_CONNECT_TIMEOUT);
		socketConnector.setWriterIdleTime(DEFAULT_CONNECT_TIMEOUT);
		socketConnector.setBothIdleTime(DEFAULT_CONNECT_TIMEOUT);

		socketConnector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory()));
		
		ClientIoHandler ioHandler = new ClientIoHandler();
		socketConnector.setHandler(ioHandler);
	}

	public void sendMessage(final String msg) {
		InetSocketAddress addr = new InetSocketAddress(HOST, PORT);
		ConnectFuture cf = socketConnector.connect(addr);
		try {
			cf.awaitUninterruptibly();
			cf.getSession().write(msg);
			System.out.println("send message " + msg);
		} catch (RuntimeIoException e) {
			if (e.getCause() instanceof ConnectException) {
				try {
					if (cf.isConnected()) {
						cf.getSession().close();
					}
				} catch (RuntimeIoException e1) {
				}
			}
		}
	}

	public static void main(String[] args) throws InterruptedException {
		MinaClient clent = new MinaClient();
		for (int i = 0; i < 1; i++) {
			System.err.println(i);
			clent.sendMessage("Hello World " + i);
		}
		clent.getSocketConnector().dispose();
		//System.exit(0);
	}

	public SocketConnector getSocketConnector() {
		return socketConnector;
	}

	public void setSocketConnector(SocketConnector socketConnector) {
		this.socketConnector = socketConnector;
	}
	
	
}

class ClientIoHandler extends IoHandlerAdapter {

	private void releaseSession(IoSession session) throws Exception {
		System.out.println("releaseSession");
		if (session.isConnected()) {
			session.closeOnFlush();
		}
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		System.out.println("sessionOpened");
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		System.out.println("sessionClosed");
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		System.out.println("sessionIdle");
		try {
			releaseSession(session);
		} catch (RuntimeIoException e) {
		}
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		System.out.println("Receive Server message " + message);

		super.messageReceived(session, message);

		releaseSession(session);
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		System.out.println("exceptionCaught");
		cause.printStackTrace();
		releaseSession(session);
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		System.out.println("messageSent");
		super.messageSent(session, message);
	}

}
 
分享到:
评论

相关推荐

    Mina实现RPC的例子

    5. **创建Client端**:在客户端,也需要创建一个Mina连接器,通过连接器与服务端建立连接。然后,发送RPC请求并处理响应。 ```java Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup) ....

    Mina官网例子之时间服务器

    - **Server端**:在时间服务器中,Mina会创建一个Acceptor,监听特定的端口,等待客户端连接。当客户端连接建立后,Acceptor会创建一个Session对象,用于管理与该客户端的通信。然后,一个自定义的过滤器(例如,...

    Mina2.0.0_RC1 例子

    src源码包下的test.mina.server.StartServer.java是启动服务器 test源码包下的socket.client.StartClient.java是启动客户端 日志记录在log目录下 lib下有完整的引用jar包 下载后记得评论和评分啊,可以返回资源分,...

    Apache mina框架入门教程

    在Mina 2.0版本中,框架分为Server端和Client端,两者都在通信结构中扮演着类似的角色,将网络通信与业务逻辑分离,使得开发者可以专注于数据处理和业务实现。Mina 的执行流程主要包括以下几个关键组件: 1. **...

    mina中文开发手册.pdf

    Mina框架中包括了对服务端(Server)和客户端(Client)的封装,使得构建网络通信应用变得简单易行。 Mina框架的核心组件和流程包括以下几个部分: 1. IoService:这是负责建立套接字连接的接口,在单一线程上运行...

    Android MiNa 通讯实现

    这个例子将详细介绍如何在Android环境中实现MiNa进行文本传输。 ### 1. MiNa核心概念 MiNa基于Java的NIO(Non-blocking I/O)模型,提供了事件驱动、非阻塞I/O的网络通信库。主要包含以下几个核心组件: - **...

    Android C/S结构代码

    在Android平台上构建C/S(Client/Server)架构的应用程序时,常常会涉及到网络通信技术。Apache Mina是一个轻量级、高性能的网络应用框架,它简化了开发过程,特别是对于TCP/IP协议栈的处理,例如Socket编程。在这个...

    telnetd-2_0.zip_java 2 telnet_java telnet server_java 实现Telnet服务

    在这个例子中,服务器启动后会监听23端口,当客户端连接时,创建一个新的线程来处理每个连接,以确保服务器能同时处理多个客户端请求。`ClientHandler`类负责读取客户端发送的命令,并向客户端返回响应。`process...

    mima框架所需的包集合

    5. **mina-client-server**:MIMA可能提供客户端和服务器端的实现,支持网络通信,这在构建分布式系统时非常有用。 6. **mina-integration**:这个部分可能是与其他流行库(如Spring、Hibernate等)的整合模块,...

    JAVA上百实例源码以及开源项目源代码

    5个目标文件,演示Address EJB的实现 ,创建一个EJB测试客户端,得到名字上下文,查询jndi名,通过强制转型得到Home接口,getInitialContext()函数返回一个经过初始化的上下文,用client的getHome()函数调用Home接口...

Global site tag (gtag.js) - Google Analytics