Mina客户端Client和Server对象传输demo

最基本的那个例子,也就是官网上的那个demo,我就不说了...

1、demo地址:http://weavesky.com/2010/02/19/mina-article-2/

但是我们实际项目中,肯定比不是如此的传输一两个数据的,我们需要传对象...老样子在此上传demo的源代码

此例子参考了himi的博文,博文地址:http://www.himigame.com/category/apache-mina

官网网站:http://mina.apache.org/mina-project/userguide/user-guide-toc.html

2、依赖的包:

mina-core-2.0.7.jar

slf4j-api-1.7.2.jar

slf4j-jdk14-1.7.2.jar

slf4j-log4j12-1.7.2.jar

3、客户端和服务端目录结构图:


一、Server

1、MinaServer

package com.potter;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class MinaServer {
	private static final int bindPort=8899;
	public static void main(String[] args){
		SocketAcceptor acceptor = new NioSocketAcceptor();
		
		DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
		
		ProtocolCodecFilter filter= new ProtocolCodecFilter(new HCoderFactory(Charset.forName("UTF-8"))); 
		//添加编码过滤器 处理乱码问题、编码问题
		chain.addLast("objectFilter",filter);
		//设置核心消息业务处理器
		acceptor.setHandler(new MinaServerHanlder());
		
		try {
			// 绑定端口
			acceptor.bind(new InetSocketAddress(bindPort));
		} catch (IOException e) {
			 System.out.println("Mina Server start for error!"+bindPort);
			e.printStackTrace();
		}
		
		System.out.println("Mina Server run done! on port:"+bindPort);
	}
}

2、MinaServerHanlder

package com.potter;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

public class MinaServerHanlder extends IoHandlerAdapter {
	private int count = 0;

	public void sessionCreated(IoSession session) {
		System.out.println("新客户端连接");
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		count++;
		System.out.println("第 " + count + " 个 client 登陆!address: : "
				+ session.getRemoteAddress());
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		session.close();
		System.out.println("I'm Client &&  I closed!");
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		// TODO Auto-generated method stub
		PlayerAccount_Entity ho = (PlayerAccount_Entity) message;
		System.out.println("Client message="+ho.getId()+ho.getName()+ho.getEmailAdress()+ho.getSex()); 
        
//     	session.write(ho);
	}
}

3、HCoderFactory

package com.potter;


import java.nio.charset.Charset;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder;

public class HCoderFactory implements ProtocolCodecFactory {     
	private final HEncoder encoder;    
	private final HDecoder decoder;     
	public HCoderFactory() {
		this(Charset.defaultCharset());    
	}     
	public HCoderFactory(Charset charSet) {        
		this.encoder = new HEncoder(charSet);        
		this.decoder = new HDecoder(charSet);    
	}
	@Override
	public ProtocolDecoder getDecoder(IoSession arg0) throws Exception {
		// TODO Auto-generated method stub
		return decoder;
	}
	@Override
	public ProtocolEncoder getEncoder(IoSession arg0) throws Exception {
		// TODO Auto-generated method stub
		return encoder;
	}     
	
}

4、HEncoder

package com.potter;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class HEncoder implements ProtocolEncoder{
	private final Charset charset;

	public HEncoder(Charset charset) {
		this.charset = charset;
	}

	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		CharsetEncoder ce = charset.newEncoder();
		PlayerAccount_Entity paEntity = (PlayerAccount_Entity) message;
		IoBuffer buffer = IoBuffer.allocate(100).setAutoExpand(true);
		buffer.putInt(paEntity.getId());
		buffer.putString(paEntity.getName(), ce);
		buffer.putString(paEntity.getEmailAdress(), ce);
		buffer.putInt(paEntity.getSex());
		buffer.flip();
		out.write(buffer);
	}

	@Override
	public void dispose(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		
	}
}

5、HDecoder

package com.potter;


import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class HDecoder extends CumulativeProtocolDecoder {
	private final Charset charset;

	public HDecoder(Charset charset) {
		this.charset = charset;
	}

	@Override
	protected boolean doDecode(IoSession arg0, IoBuffer message,
			ProtocolDecoderOutput arg2) throws Exception {
		CharsetDecoder cd = charset.newDecoder();
		int id=0;
		if(message.remaining()>=4){
			id=message.getInt();
		}
		String name = message.getString(cd);
		String emailAdress=message.getString(cd);
		int sex=0;
		if(message.remaining()>=4){
			sex=message.getInt();
		}
		
		PlayerAccount_Entity paEntity = new PlayerAccount_Entity(id,name,emailAdress,sex);
		
		arg2.write(paEntity);
		return true;
	}
}

6、PlayerAccount_Entity

package com.potter;

public class PlayerAccount_Entity{
	private int id;    
	private String name;    
	private String emailAdress;    
	private int sex;// 0=man 1=woman
	
	public PlayerAccount_Entity(int id,String name,String emailAdress,int sex){
		this.id=id;
		this.name=name;
		this.emailAdress=emailAdress;
		this.sex=sex;
	}
	 
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmailAdress() {
		return emailAdress;
	}
	public void setEmailAdress(String emailAdress) {
		this.emailAdress = emailAdress;
	}
	public int getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}
}


二、Client

1、MinaClient

package com.potter;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

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.transport.socket.nio.NioSocketConnector;

public class MinaClient {
	private static final int bindPort=8899;
	public static void main(String[] args){
		// 创建一个socket连接      
		NioSocketConnector connector=new NioSocketConnector();
		// 获取过滤器链        
		DefaultIoFilterChainBuilder chain=connector.getFilterChain();
		
		ProtocolCodecFilter filter= new ProtocolCodecFilter(new HCoderFactory(Charset.forName("UTF-8"))); 
		// 添加编码过滤器 处理乱码、编码问题  
		chain.addLast("objectFilter",filter);
		// 消息核心处理器     
		connector.setHandler(new MinaClientHanlder());
		// 设置链接超时时间     
		connector.setConnectTimeoutCheckInterval(30);
		// 连接服务器,知道端口、地址    
		ConnectFuture cf = connector.connect(new InetSocketAddress("localhost",bindPort));
		// 等待连接创建完成    
		cf.awaitUninterruptibly();
		cf.getSession().getCloseFuture().awaitUninterruptibly();
		connector.dispose();
	}
}


2、MinaClientHanlder

package com.potter;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

public class MinaClientHanlder extends IoHandlerAdapter{
	
	public void sessionOpened(IoSession session) throws Exception {
		 PlayerAccount_Entity ho = new PlayerAccount_Entity(10,"Potter","[email protected]",0);
	     session.write(ho);
    }
	
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		PlayerAccount_Entity ho = (PlayerAccount_Entity) message;        
		System.out.println("Server Say:name:" + ho.getName());
	}
	
	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		session.close();
	}
}


好了,共同的就不穿了....

你可能感兴趣的:(Mina客户端Client和Server对象传输demo)