关于mina

      mina框架是一个基于tcp/ip,udp/ip协议的一个通信框架,他和netty都是出自一人之手,大体的结构都差不多,首先来介绍怎么建立一个mina的服务端:

 一,服务端的建立:

        先来看一个例子,然后我们依次来分析:

public static void main(String[] args) {

		IoAcceptor acceptor = new NioSocketAcceptor() ;
		acceptor.getSessionConfig().setReadBufferSize(2048) ;
		
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10) ; //读写通道在10秒内无任何操作进入空闲状态
		/**
		 * 过滤器,通过编解码器工厂来对字符串进行编解码处理
		 */
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf-8"),LineDelimiter.WINDOWS.getValue(),LineDelimiter.WINDOWS.getValue() )));
		/*new TextLineCodecFactory( <span style="white-space:pre"> </span>Charset.forName("UTF-8")
											<span style="white-space:pre"> </span>LineDelimeter.WINDOS.getValue(),
											<span style="white-space:pre"> </span>LineDelimeter.WINDOS.getValue()
				)*/
		/*acceptor.getFilterChain().addLast("codec",  
                new ProtocolCodecFilter(  
                        new ObjectSerializationCodecFactory()));  */
		acceptor.setHandler(new ServiceHandler()) ;
		
		try {
			acceptor.bind(new InetSocketAddress(9132));
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	
	}

 在这个例子中,就是启动了一个服务器端,首先IoAcceptor是服务端的一个重要的类,mina框架用的都是NIO所以,一般是new一个NioSocketAcceptor

申明建立acceptor对象后,便需要对他进行配置,配置发送字节的大小,接收消息字节的大小,多长时间无通信进入休眠,编码器,解码器(这里的编码器主要是简单的utf-8字符串编码器,后面会详细介绍编码器和解码器),注册服务器端接收消息发送消息的Handler,最后是绑定端口,这是在最后执行,配置都需要在bing之前完成,ip为默认本机ip,其中最重要的就是Handler了,下面贴出handler的代码

public class ServiceHandler extends IoHandlerAdapter{
	
	public void sessionOpened(IoSession session )throws Exception{
		
		
	}
	@Override
    public void exceptionCaught(IoSession session, Throwable cause)
	    throws Exception {
	
    }
	@Override
	public void  messageSent(IoSession session, Object message)throws Exception{
		
		
	}
	@Override
	public void messageReceived(IoSession session, Object message)throws Exception{
		
	}
	@Override
	public void sessionCreated(IoSession session) throws Exception{
		
	}
	@Override
	public void sessionClosed(IoSession session){
		
			}
		}
	}
	

}

 可以看到handler类都需要继承IoHandlerAdapter,这是mina框架的一个Handler适配类,也就是多有的handler都要按照这个规则来写,继承后,需要覆盖父类的方法来处理连接的session以及消息,netty是通过channel来读写消息,而mina则是通过session,先来说一下这些方法的作用,

public void exceptionCaught(IoSession session, Throwable cause)这是一个异常处理的方法,如果对自己有信息,可以不要,不过一般还是添加为妙,因为也不知道为什么,确实会有一些不知道的异常出现,

public void sessionOpened(IoSession session )session打开时触发

public void  messageSent(IoSession session, Object message)发送消息是触发,也就是说当你使用session.write(Object)后就会调用这个方法

public void messageReceived(IoSession session, Object message)接收消息时触发,session为连接session,message为接收到的消息,如果你发的是String,则可以通过String  mess = (String)message来获取消息内容

public void sessionCreated(IoSession session)连接建立是触发

public void sessionClosed(IoSession session)连接关闭时触发

二:客户端的建立

先来看一个客户端的例子:

public void connect(String ip , String port){
                IoConnector connector = null ;
		connector = new NioSocketConnector();
		connector.setConnectTimeoutMillis(30000);
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("gbk"),LineDelimiter.WINDOWS.getValue(),LineDelimiter.WINDOWS.getValue())));
		connector.setHandler(new ClientHandler());
		connector.connect(new InetSocketAddress(ip	 , Integer.valueOf(port))) ;
		this.setTitle("已连接至服务器") ;

	}

 mina的服务器端是申明一个IoAcceptor类,客户端则是申明一个IoConnector类,并创建一个NioSocketConnector对象,接着是对这个对象进行设置和注册,一般的设置和服务器端差不多,这里仅供参考只是设置了需要的,一行的客户端和服务器端一样需要注册一个handler来处理谁session以及接收消息,handler和服务器端的一样需要继承IoHandlerAdapter,方法也是一样,这里就不多说了,根据这些类容,我写了一个可以局域网联机的中国象棋的小游戏,主要流程是首先启动服务器端,来处理客户端的连接,和客户端之间的通信,客户端启动后会自动连接服务器,连接成功并匹配到对手后就会开始游戏,有兴趣的同学可以看一下,下面贴出代码:

客户端主类:

package ChinaChess;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import org.apache.mina.core.service.IoConnector;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;


public class MainFrame extends JFrame{
	public static int length = 100 ;
	public static ExecutorService exe = Executors.newCachedThreadPool();
	/**颜色  在链接后初始化 1 位红色 -1 为 黑色*/
	public static int color = 0 ;
	public static int state = -1 ;
	public static int step = -1 ;
	public static int fresh = 0 ;
	public static Point selectPoint = null ;
	private static IoConnector connector = null ;
	public static ConcurrentHashMap<Point, Chess> chesses = new ConcurrentHashMap<Point, Chess>();
	public MainFrame(){

		this.setBounds(500 , 20 ,900 ,1050) ;
		this.setLayout(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setResizable(false);

		JMenuBar menubar = new JMenuBar() ;
		JMenu menu = new JMenu("Start");
		JMenuItem item = new JMenuItem("reStart");
		item.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				
			}
		});
		menu.add(item);
		menubar.add(menu);
		
		this.setJMenuBar(menubar);
		this.setVisible(true);
	
		this.addMouseListener(new MouseListener() {
			
			@Override
			public void mouseReleased(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mousePressed(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseExited(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseClicked(MouseEvent e) {
				// TODO Auto-generated method stub
				int x = getX(e.getX());
				int y = getY(e.getY());
				
			if(state != -1 && step == 1 ){
					Point point = new Point(x ,y);
					Chess c = chesses.get(point);
					if(c != null && c.getColor() == color){
						selectPoint = point ;	
					}
					else if(selectPoint != null ){
						
						Chess cs = chesses.get(selectPoint);
						System.out.println(cs.toString());
						ArrayList<Point> ps = cs.getNextStep();
						if(ChessStep.simpleDiscre(cs , point)){
							if(chesses.contains(point)){
								Chess enemy = chesses.get(point);
								if(enemy.getColor() == (0 - color)){
									
									cs.setPoint(point) ;
									chesses.remove(selectPoint);
									chesses.put(point, cs);

									ClientHandler.session.write((int)selectPoint.getX()+" "+(int)selectPoint.getY()+" "+(int)point.getX()+" "+(int)point.getY());
									selectPoint = null ;
									step = -1 ;
									if(enemy.getType().equals("Super")){
										ClientHandler.session.write("03 00 00 00");
										JOptionPane.showMessageDialog(new JFrame(), "你赢了!", "提醒", JOptionPane.DEFAULT_OPTION) ;
										ClientHandler.session.write("04 01 00 00");
									}
								}
								
							}
							else {
								cs.setPoint(point) ;
								chesses.remove(selectPoint);
								chesses.put(point, cs);
								ClientHandler.session.write((int)selectPoint.getX()+" "+(int)selectPoint.getY()+" "+(int)point.getX()+" "+(int)point.getY());
								selectPoint = null ;
								step = -1 ;
							}
						}
							
							
							
						
					}
				}
				repaint();
				
				
			}
		});
		exe.submit(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					if(fresh>0){
						repaint();
						fresh = 0 ;
					}
					try {
						Thread.sleep(1000) ;
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		this.addWindowListener(new WindowListener() {
			
			@Override
			public void windowOpened(WindowEvent arg0) {
				// TODO Auto-generated method stub
				repaint();
			}
			
			@Override
			public void windowIconified(WindowEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void windowDeiconified(WindowEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void windowDeactivated(WindowEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void windowClosing(WindowEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void windowClosed(WindowEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void windowActivated(WindowEvent arg0) {
				// TODO Auto-generated method stub
				repaint();
			}
		});
		
	}
	private int getX(int x ){
		int add = (x-50) / 100 ;
		int step1 =(x-50)  % 100 ;
		int result = -1;
		if(step1 >= 60 ){
			result = add*100 + 100 ;
			
		}
		else if(step1 < 40){
			result = add*100 ;
		}
		return result ;
	}
	private int getY(int y ){
		int add = (y-100) / 100 ;
		int step1 =(y-100)  % 100 ;
		int result = -1;
		if(step1 >= 60 ){
			result = add*100 + 100 ;
			
		}
		else if(step1 < 40){
			result = add*100 ;
		}
		return result ;
	}
	
	public static void init(){
		chesses.clear() ; 
		Chess su = SuperChess.getChess(1) ;
		ChinaChess.Chess su1 = SuperChess.getChess(-1) ;
		chesses.put(su.getPoint(), su) ;
		chesses.put(su1.getPoint(), su1);
		/**士*/
		Chess  RBache = BachelorChess.getChess(1) ;
		RBache .setPoint(new Point(300 , 0)) ;
		chesses.put(new Point(300 , 0), RBache);
		Chess  RBache1 = BachelorChess.getChess(1) ;
		RBache1 .setPoint(new Point(500 , 0)) ;
		chesses.put(new Point(500 , 0), RBache1);
		Chess  BBache = BachelorChess.getChess(-1) ;
		BBache .setPoint(new Point(300 , 900)) ;
		chesses.put(new Point(300 , 900), BBache);
		Chess  BBache1 = BachelorChess.getChess(-1) ;
		BBache1 .setPoint(new Point(500 , 900)) ;
		chesses.put(new Point(500 , 900), BBache1);
		/**象*/
		Chess RChacel = ChancellorChess.getChess(1) ;
		RChacel.setPoint(new Point(200 , 0));
		chesses.put(new Point(200 , 0), RChacel);
		Chess RChacel1 = ChancellorChess.getChess(1) ;
		RChacel1.setPoint(new Point(600 , 0));
		chesses.put(new Point(600 , 0), RChacel1);
		Chess BChacel = ChancellorChess.getChess(-1) ;
		BChacel.setPoint(new Point(200 , 900));
		chesses.put(new Point(200 , 900), BChacel);
		Chess BChacel1 = ChancellorChess.getChess(-1) ;
		BChacel1.setPoint(new Point(600 , 900));
		chesses.put(new Point(600 , 900), BChacel1);
		/**马*/
		Chess Rhorse = HorseChess.getChess(1) ;
		Rhorse.setPoint(new Point(100 , 0)) ;
		chesses.put(new Point(100 , 0), Rhorse);
		Chess Rhorse1 = HorseChess.getChess(1) ;
		Rhorse1.setPoint(new Point(700 , 0)) ;
		chesses.put(new Point(700 , 0), Rhorse1);
		Chess Bhorse = HorseChess.getChess(-1) ;
		Bhorse.setPoint(new Point(100 , 900)) ;
		chesses.put(new Point(100 , 900), Bhorse);
		Chess Bhorse1 = HorseChess.getChess(-1) ;
		Bhorse1.setPoint(new Point(700 , 900)) ;
		chesses.put(new Point(700 , 900), Bhorse1);
		/**车*/
		Chess Rcar = CarChess.getChess(1);
		Rcar.setPoint(new Point(0 , 0)) ;
		chesses.put(new Point(0 , 0), Rcar);
		Chess Rcar1 = CarChess.getChess(1);
		Rcar1.setPoint(new Point(800 , 0)) ;
		chesses.put(new Point(800 , 0), Rcar1);
		Chess Bcar = CarChess.getChess(-1);
		Bcar.setPoint(new Point(0 , 900)) ;
		chesses.put(new Point(0 , 900), Bcar);
		Chess Bcar1 = CarChess.getChess(-1);
		Bcar1.setPoint(new Point(800 , 900)) ;
		chesses.put(new Point(800 , 900), Bcar1);
		/**炮*/
		Chess Rcannon = CannonChess.getChess(1);
		Rcannon.setPoint(new Point(100,200));
		chesses.put(new Point(100 , 200), Rcannon);
		Chess Rcannon1 = CannonChess.getChess(1);
		Rcannon1.setPoint(new Point(700,200));
		chesses.put(new Point(700 , 200), Rcannon1);
		Chess Bcannon = CannonChess.getChess(-1);
		Bcannon.setPoint(new Point(100,700));
		chesses.put(new Point(100 , 700), Bcannon);
		Chess Bcannon1 = CannonChess.getChess(-1);
		Bcannon1.setPoint(new Point(700,700));
		chesses.put(new Point(700 , 700), Bcannon1);
		
		Chess Rarm = ArmsChess.getChess(1);
		Rarm.setPoint(new Point(0 , 300));
		chesses.put(new Point(0 , 300), Rarm);
		Chess Rarm1 = ArmsChess.getChess(1);
		Rarm1.setPoint(new Point(200 , 300));
		chesses.put(new Point(200 , 300), Rarm1);
		Chess Rarm2 = ArmsChess.getChess(1);
		Rarm2.setPoint(new Point(400 , 300));
		chesses.put(new Point(400 , 300), Rarm2);
		Chess Rarm3 = ArmsChess.getChess(1);
		Rarm3.setPoint(new Point(600 , 300));
		chesses.put(new Point(600 , 300), Rarm3);
		Chess Rarm4 = ArmsChess.getChess(1);
		Rarm4.setPoint(new Point(800 , 300));
		chesses.put(new Point(800 , 300), Rarm4);
		
		Chess Barm = ArmsChess.getChess(-1);
		Barm.setPoint(new Point(0,600));
		chesses.put(new Point(0 , 600), Barm);
		Chess Barm1 = ArmsChess.getChess(-1);
		Barm1.setPoint(new Point(200,600));
		chesses.put(new Point(200 , 600), Barm1);
		Chess Barm2 = ArmsChess.getChess(-1);
		Barm2.setPoint(new Point(400,600));
		chesses.put(new Point(400 , 600), Barm2);
		Chess Barm3 = ArmsChess.getChess(-1);
		Barm3.setPoint(new Point(600,600));
		chesses.put(new Point(600 , 600), Barm3);
		Chess Barm4 = ArmsChess.getChess(-1);
		Barm4.setPoint(new Point(800,600));
		chesses.put(new Point(800 , 600), Barm4);
	}
	@Override
	public void paint(Graphics g){
		super.paint(g);
		g.setColor(Color.GRAY);
		g.fillRect(0, 50, 900, 1050);
		g.setColor(Color.BLACK);
		for(int i = 50 ;i <= 850 ; i += 100 ){
			for(int j = 50 ; j <= 950 ; j += 100){
				g.drawLine(50, j+50 , 850, j+50);
				g.drawLine(i, 100, i, 500) ;
				g.drawLine(i, 600, i, 1000) ;
				
			}
		}
		/**画棋盘*/
		boolean flag = false ;
		for(int x = 350 ; x <= 550 ; x += 10 ){
			if(flag){
				g.drawLine(x, x+50-300, x+10, x+60-300) ;
				g.drawLine(x, 250-x+400, x+10, 250-x+400-10) ;
				if(x != 550){
					g.drawLine(x, x+50-300+700, x+10, x+60-300+700) ;
					g.drawLine(x, 250-x+400+700, x+10, 250-x+400-10+700) ;
				}
			}
			flag = ! flag ;
		}
		/**画棋子*/
		
		
		for(Point p : chesses.keySet()){
				Chess ch = chesses.get(p);
				drawChess(ch, g) ;
			
		}
		/**画选中的点*/
		
		
	}
	public void connect(String ip , String port){
		connector = new NioSocketConnector();
		connector.setConnectTimeoutMillis(30000);
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("gbk"),LineDelimiter.WINDOWS.getValue(),LineDelimiter.WINDOWS.getValue())));
		connector.setHandler(new ClientHandler());
		connector.connect(new InetSocketAddress(ip	 , Integer.valueOf(port))) ;
		this.setTitle("已连接至服务器") ;

	}
	public static void drawChess(Chess chess , Graphics g){

		int x = (int)chess.getPoint().getX() - 40 + 50 ;
		int y = (int)chess.getPoint().getY() - 40 + 50;
		if(selectPoint!=null){
			if(chess.getPoint().getX() == selectPoint.getX() && chess.getPoint().getY() == selectPoint.getY()){
				chess.setBgColor(new Color(224 , 86 , 39));
			}
			else {
				chess.setBgColor(new Color(117 , 108 , 104)) ;
			} 
		}
		else{
			chess.setBgColor(new Color(117 , 108 , 104)) ;
		}
		g.setColor(chess.getBgColor());
		g.fillOval(x, y+50, 80, 80) ;
		
		if(chess.getColor()==1){
			g.setColor(Color.RED);
		}
		else if(chess.getColor()==-1){
			g.setColor(Color.BLACK);
		}
		g.setFont(new Font("华文行楷" , 20 , 60)) ;
		String chessName = chess.getName() ;
 		g.drawString(chessName, x+10, y+50+50) ;
		
	
	}
	public static void main(String[] args) {
		new MainFrame().connect("10.10.11.37", "9132") ;
	}
}

 客户端handler:

package ChinaChess;

import java.awt.Point;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

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


import tools.StringKit;



public class ClientHandler extends IoHandlerAdapter{

	private static final Logger logger = Logger.getLogger(ClientHandler.class);
	public static IoSession session = null ;
	public void sessionOpened(IoSession session )throws Exception{
		
		logger.info("Open") ;
	}
	@Override
    public void exceptionCaught(IoSession session, Throwable cause)
	    throws Exception {
	if (!(cause instanceof IOException)) {
	    cause.printStackTrace();
	}
    }
	@Override
	public void  messageSent(IoSession session, Object message)throws Exception{
		logger.info("发送的消息:"+message.toString() + session.getRemoteAddress());
		
	}
	@Override
	public void messageReceived(IoSession session, Object message)throws Exception{
		String mess = (String) message ;
		String me[] = StringKit.separate(mess, " ") ;
		if(me.length == 4){
			if(me[0].equals("01")){
				if(me[1].equals("01")){
					MainFrame.state = 1 ;
					MainFrame.fresh = 1 ;
				}
				else if(me[1].equals("02")){
					MainFrame.state = -1 ;
					MainFrame.fresh = 1 ;
				}
			}
			else if(me[0].equals("02")){
				if(me[1].equals("01")){
					MainFrame.color = 1 ;
					MainFrame.init();
					MainFrame.step = 1 ;
					MainFrame.fresh = 1 ;
				}
				else if(me[1].equals("02")){
					MainFrame.color = -1 ;
					MainFrame.init();
					MainFrame.fresh = 1 ;
					
				}
			}
			else if(me[0].equals("03")){
				JOptionPane.showMessageDialog(new JFrame(), "你输了!", "提醒", JOptionPane.DEFAULT_OPTION) ;
			}
			else if(me[0].equals("04")&&me[1].equals("01")){
				int n = JOptionPane.showConfirmDialog(new JFrame(), "是否重新开始...", "确认对话框", JOptionPane.YES_NO_OPTION) ;
				if(n == JOptionPane.YES_OPTION){
					session.write("04 00 00 00");
					
				}
				
			}
			else {
				int x1 = Integer.parseInt(me[0]);
				int y1 = Integer.parseInt(me[1]);
				int x2 = Integer.parseInt(me[2]);
				int y2 = Integer.parseInt(me[3]);
				Point p1 = new Point(x1 , y1 );
				Point p2 = new Point(x2 , y2 );
				Chess c = MainFrame.chesses.get(p1) ;
				c.setPoint(p2);
				MainFrame.chesses.remove(p1);
				MainFrame.chesses.put(p2, c);
				MainFrame.step = 1 ;
				MainFrame.fresh = 1 ;
			}
			
			
		}
	}
	@Override
	public void sessionCreated(IoSession session) throws Exception{

		this.session = session ;
		
	}
	 
	@Override
	public void sessionClosed(IoSession session) throws Exception{
		this.session = null ;
	}

}

 接着是一些棋子的类,所有棋子都是继承自Chess这个抽象类:

package ChinaChess;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;

public abstract class Chess {
	/**背景颜色*/
	private Color bgColor ;
	/**类别*/
	private String Type ;
	/**颜色*/
	private	int color ;
	/**名称*/
	private String Name ;
	/**坐标*/
	private Point point ;
	/**允许走的点*/
	private ArrayList<Point> allowPoint ;
	/**获取下一步可以走的点*/
	public abstract ArrayList<Point> getNextStep();
	public Chess(){
		this.bgColor = new Color(117 , 108 , 104) ;
	}
	public static boolean checkPoint(Point p ){
		int x = (int) p.getX() ;
		int y = (int) p.getY() ;
		if(x < 0 || y < 0 || x > 800 || y > 900 ){
			return false ;
		}
		else return true ;
	}
	public void draw(Graphics g){
		int x = (int)this.point.getX() - 40 ;
		int y = (int)this.point.getY() - 40 ;
		if(color == 1 ){
			g.setColor(Color.RED);
		}
		else if(color== -1){
			g.setColor(Color.BLACK);
		}
		g.fillOval(x, y, 80, 80) ;
		g.setColor(Color.WHITE);
		g.setFont(new Font("华文行楷" , 20 , 20));
		g.drawString(this.Name, x+20, y+20);
	}
	public String getType() {
		return Type;
	}
	public void setType(String type) {
		Type = type;
	}
	public int getColor() {
		return color;
	}
	public void setColor(int color) {
		this.color = color;
	}
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public Point getPoint() {
		return point;
	}
	public void setPoint(Point point) {
		this.point = point;
	}
	public ArrayList<Point> getAllowPoint() {
		return allowPoint;
	}
	public void setAllowPoint(ArrayList<Point> allowPoint) {
		this.allowPoint = allowPoint;
	}
	
	public Color getBgColor() {
		return bgColor;
	}
	public void setBgColor(Color bgColor) {
		this.bgColor = bgColor;
	}
	public String toString(){
		return Type+" "+Name +" ("+point.getX()+" "+point.getY()+")" ;
	}
	public static void main(String[] args) {
		System.out.println("a");
	}
}
package ChinaChess;

import java.awt.Color;
import java.awt.Point;
import java.util.ArrayList;

public class ArmsChess extends Chess{
	public ArmsChess(){
		this.setType("Arms") ;
	}
	@Override
	public ArrayList<Point> getNextStep() {
		// TODO Auto-generated method stub
		Point p = this.getPoint();
		ArrayList<Point> list = new ArrayList<Point>();
		int x = (int)p.getX() ;
		int y = (int)p.getY() ;
		Point p1 = new Point(x- 100  , y );
		if(checkPoint(p1)){
			list.add(p1);
		}
		Point p2 = new Point(x+100   , y );
		if(checkPoint(p2)){
			list.add(p2);
		}
		Point p3 = new Point(x  , y - 100);
		if(checkPoint(p3)){
			list.add(p3);
		}
		Point p4 = new Point(x  , y + 100);
		if(checkPoint(p4)){
			
			list.add(p4);
		}
		return list;
	}
	public static Chess getChess(int color) {

		   // TODO Auto-generated method stub 
		ArmsChess chess = new ArmsChess() ;
		if(color == 1 ){
			chess.setColor(1) ;
			chess.setName("兵");
		}
		else if(color == -1){
			chess.setColor(-1) ;
			chess.setName("卒");
		}
		return chess;
	}
	public static void main(String[] args) {
	System.out.println(" \""+"\" ");
	}
	
}
package ChinaChess;

import java.awt.Point;
import java.util.ArrayList;

public class BachelorChess extends Chess{
	public BachelorChess(){
		this.setType("Bachelor") ;
		ArrayList<Point> allowP = new ArrayList<Point>();
		allowP.add(new Point(300 , 0));
		allowP.add(new Point(500 , 0));
		allowP.add(new Point(400 , 100));
		allowP.add(new Point(300 , 200));
		allowP.add(new Point(500 , 200));
		allowP.add(new Point(300 , 900));
		allowP.add(new Point(500 , 900));
		allowP.add(new Point(400 , 800));
		allowP.add(new Point(300 , 700));
		allowP.add(new Point(500 , 700));
		this.setAllowPoint(allowP);
	}
	@Override
	public ArrayList<Point> getNextStep() {
		// TODO Auto-generated method stub
		Point p = this.getPoint();
		ArrayList<Point> next = new ArrayList<Point>();
		int x = (int)p.getX();
		int y = (int)p.getY();
		next.add(new Point(x -MainFrame.length, y-MainFrame.length)) ;
		next.add(new Point(x +MainFrame.length, y-MainFrame.length)) ;
		next.add(new Point(x -MainFrame.length, y+MainFrame.length)) ;
		next.add(new Point(x +MainFrame.length, y+MainFrame.length)) ;
		next.retainAll(getAllowPoint()) ;
			return next ;
		
		
	}
	public static Chess getChess(int color) {
		// TODO Auto-generated method stub
		BachelorChess chess = new BachelorChess() ;
		if(color == 1 ){
			chess.setColor(1) ;
			chess.setName("士");
		}
		else if(color == -1){
			chess.setColor(-1) ;
			chess.setName("仕");
		}
		return chess;
	}

}
package ChinaChess;

import java.awt.Point;
import java.util.ArrayList;

import javax.xml.crypto.dsig.CanonicalizationMethod;

public class CannonChess extends Chess{
	public CannonChess(){
		this.setType("Cannon") ;
		
	}
	@Override
	public ArrayList<Point> getNextStep() {
		// TODO Auto-generated method stub
		Point p = this.getPoint();
		ArrayList<Point> list = new ArrayList<Point>();
		for(int x = 0 ; x < 800 ; x += 100){
			for(int y = 0 ; y < 900 ; y += 100){
				Point p1 = new Point(x , y );
				if((p1.getX() == p.getX() && p1.getY() != p.getY()) || (p1.getY() == p.getY() && p1.getX() != p.getY())){
					if(Chess.checkPoint(p1)){
						list.add(p1);
					}
				}

			}
		}
		return list;
	}
	public static Chess getChess(int color) {
		// TODO Auto-generated method stub
		CannonChess chess = new CannonChess() ;
		if(color == 1 ){
			chess.setColor(1) ;
			chess.setName("炮");
		}
		else if(color == -1){
			chess.setColor(-1) ;
			chess.setName("炮");
		}
		return chess;
	}

}
package ChinaChess;

import java.awt.Point;
import java.util.ArrayList;

public class CarChess extends Chess{
	public CarChess(){
		this.setType("Car") ;
	}
	@Override
	public ArrayList<Point> getNextStep() {
		// TODO Auto-generated method stub
		Point p = this.getPoint();
		ArrayList<Point> list = new ArrayList<Point>();
		for(int x = 0 ; x < 800 ; x += 100){
			for(int y = 0 ; y < 900 ; y += 100){
				Point p1 = new Point(x , y );
				if((p1.getX() == p.getX() && p1.getY() != p.getY()) || (p1.getY() == p.getY() && p1.getX() != p.getY())){
					if(Chess.checkPoint(p1)){
						list.add(p1);
					}
				}

			}
		}
		return list;
	}
	public static Chess getChess(int color) {
		// TODO Auto-generated method stub
		CarChess chess = new CarChess() ;
		if(color == 1 ){
			chess.setColor(1) ;
			chess.setName("车");
		}
		else if(color == -1){
			chess.setColor(-1) ;
			chess.setName("车");
		}
		return chess;
	}

}
package ChinaChess;

import java.awt.Point;
import java.util.ArrayList;

public class ChancellorChess extends Chess{

	public ChancellorChess(){
		this.setType("Chancellor") ;
		ArrayList<Point> allowP = new ArrayList<Point>();
		allowP.add(new Point(0 , 200));
		allowP.add(new Point(200 , 0));
		allowP.add(new Point(200 , 400));
		allowP.add(new Point(400 , 200));
		allowP.add(new Point(600 , 0));
		allowP.add(new Point(600 , 400));
		allowP.add(new Point(800 , 200));
		allowP.add(new Point(0 , 700));
		allowP.add(new Point(200 , 900));
		allowP.add(new Point(200 , 500));
		allowP.add(new Point(400 , 700));
		allowP.add(new Point(600 , 900));
		allowP.add(new Point(600 , 500));
		allowP.add(new Point(800 , 700));
		this.setAllowPoint(allowP);
	}
	@Override
	public ArrayList<Point> getNextStep() {
		// TODO Auto-generated method stub
		Point p = this.getPoint();
		ArrayList<Point> next = new ArrayList<Point>();
		int x = (int)p.getX();
		int y = (int)p.getY();
		next.add(new Point(x -2*MainFrame.length, y-2*MainFrame.length)) ;
		next.add(new Point(x +2*MainFrame.length, y-2*MainFrame.length)) ;
		next.add(new Point(x -2*MainFrame.length, y+2*MainFrame.length)) ;
		next.add(new Point(x +2*MainFrame.length, y+2*MainFrame.length)) ;
		next.retainAll(getAllowPoint());
			return next ;
		
	}
	public static Chess getChess(int color) {

		// TODO Auto-generated method stub
		ChancellorChess chess = new ChancellorChess() ;
		if(color == 1 ){
			chess.setColor(1) ;
			chess.setName("相");
		}
		else if(color == -1){
			chess.setColor(-1) ;
			chess.setName("象");
		}
		return chess;
	
	}


}
package ChinaChess;

import java.awt.Point;

public class ChessStep {
	
	public static boolean simpleDiscre(Chess chess , Point point){
		String Type = chess.getType() ;
		if(Type.equals("Super")){
			return superstepJudge(chess , point);
		}
		else if(Type.equals("Bachelor")){
			return bachestepJudge(chess, point);
		}
		else if(Type.equals("Chancellor")){
			System.out.println("OK");
			return chancestepJudge(chess , point);
		}
		else if(Type.equals("Horse")){
			return horsestepJudge(chess , point);
		}
		else if(Type.equals("Car")){
			return carstepJudge(chess  , point);
		}
		else if(Type.equals("Cannon")){
			return cannonstepJudge(chess , point);
		}
		else if(Type.equals("Arms")){
			return armstepJudge(chess , point);
		}
		return false ;
	}
	private static boolean armstepJudge(Chess chess , Point p ){
		if(chess.getNextStep().contains(p)){
			if(chess.getColor() == 1){
				if((int)chess.getPoint().getY() <500){
					Point step = new Point((int)chess.getPoint().getX() , (int)chess.getPoint().getY()+100);
					if(step.equals(p)){
						return true ;
					}
					else return false ;
				}
				else if((int)chess.getPoint().getY() >=500){
					if(p.getY() < chess.getPoint().getY()){
						return false ;
					}
					else return true ;
				}
			}
			else if(chess.getColor() == -1){
				if((int)chess.getPoint().getY() >=500){
					Point step = new Point((int)chess.getPoint().getX() , (int)chess.getPoint().getY()-100);
					if(step.equals(p)){
						return true ;
					}
					else return false ;
				}
				else if((int)chess.getPoint().getY() < 500){
					if(p.getY() < chess.getPoint().getY()){
						return false ;
					}
					else return true ;
				}
			
			}
		}
		
		return false ;
	}
	private static boolean cannonstepJudge(Chess chess , Point p ){
		int num = 0 ;
		if(chess.getPoint().getX() == p.getX()){
			for(int y = (int)chess.getPoint().getY()+100 ; y < (int)p.getY() ; y+=100){
				Point po = new Point((int)p.getX() , y);
				if(MainFrame.chesses.containsKey(po)){
					num ++ ;
				}
			}
			if(num <=1 ){
				return true ;
			}
			else return false ;
		}
		else if(chess.getPoint().getY() == p.getY()){
			for(int x = (int)chess.getPoint().getX()+100 ; x < (int)p.getX() ; x+=100){
				if(MainFrame.chesses.containsKey(new Point(x , (int)p.getY()))){
					num ++ ;
				}
			}
			if(num <=1 ){
				return true ;
			}
			else return false ;
		}
		return false ;                                 
	}
	
	private static boolean carstepJudge(Chess chess , Point p ){
		if(chess.getPoint().getX() == p.getX()){
			for(int y = (int)chess.getPoint().getY()+100 ; y < (int)p.getY() ; y+=100){
				if(MainFrame.chesses.containsKey(new Point((int)p.getX() , y))){
					return false ;
				}
			}
			return true ; 
			
		}
		else if(chess.getPoint().getY() == p.getY()){
			for(int x = (int)chess.getPoint().getX()+100 ; x < (int)p.getX() ; x+=100){
				if(MainFrame.chesses.containsKey(new Point(x , (int)p.getY()))){
					return false ;
				}
			}
			return true ;
		}
		return false ;
	}
	private static boolean horsestepJudge(Chess chess , Point p ){
		
		if((chess.getPoint().getY() == (p.getY()+2*MainFrame.length) && MainFrame.chesses.containsKey(new Point((int)chess.getPoint().getX() , (int)chess.getPoint().getY()+100)))
			||(chess.getPoint().getY() == (p.getY()-2*MainFrame.length) && MainFrame.chesses.containsKey(new Point((int)chess.getPoint().getX() , (int)chess.getPoint().getY()-100)))
			||(chess.getPoint().getX() == (p.getY()+2*MainFrame.length) && MainFrame.chesses.containsKey(new Point((int)chess.getPoint().getX()+100 , (int)chess.getPoint().getY())))
			||(chess.getPoint().getX() == (p.getY()-2*MainFrame.length) && MainFrame.chesses.containsKey(new Point((int)chess.getPoint().getX()-100 , (int)chess.getPoint().getY())))
			
				){
			return false ;
		}
		if(chess.getNextStep().contains(p) /*&& !MainFrame.chesses.contains(p)*/){
			return true ;
		}
		return false ;
	}
	private static boolean chancestepJudge(Chess chess , Point p ){
		if(chess.getNextStep().contains(p)/* && !MainFrame.chesses.contains(p)*/){
			return true ;
		}
		return false ;
	}
	private static boolean bachestepJudge(Chess chess , Point p){
		int Absox = Math.abs((int)chess.getPoint().getX() - (int) p.getX()) ;
		int Absoy = Math.abs((int)chess.getPoint().getY() - (int) p.getY()) ;
		for(Point ps : chess.getNextStep()){
			System.out.print("( "+ps.getX()+" "+ps.getY()+" ) ");
		}
		if(Absox == 100 && Absoy == 100 && chess.getNextStep().contains(p) /*&& !MainFrame.chesses.contains(p)*/){
			return true ;
		}
		return false ;
	}
	private static boolean superstepJudge(Chess chess , Point p2){
		int Absox = Math.abs((int)chess.getPoint().getX() - (int) p2.getX()) ;
		int Absoy = Math.abs((int)chess.getPoint().getY() - (int) p2.getY()) ;
		if((Absox == 100 && Absoy == 0) ||(Absox == 0 && Absoy ==100)){
			if(chess.getNextStep().contains(p2) /*&& !MainFrame.chesses.contains(p2)*/){
				return true ;
			}
		}
		return false ;
	} 
	public static void main(String[] args) {
			Chess s = SuperChess.getChess(1);
			System.out.println(s.getClass());
			
	}
}
package ChinaChess;

import java.awt.Point;
import java.util.ArrayList;

public class HorseChess extends Chess{
	public HorseChess(){
		this.setType("Horse");
		
	}

	@Override
	public ArrayList<Point> getNextStep() {
		// TODO Auto-generated method stub
		Point p = this.getPoint();
		ArrayList<Point> list = new ArrayList<Point>();
		for(int i = 0 ; i < 8 ; i ++){
			switch(i){
			case 0 : {
				int x = (int) p.getX() - 100;
				int y = (int) p.getY() - 200;
				Point p1 = new Point(x , y ); if(Chess.checkPoint(p1)){list.add(p1);} 		} break ;
			case 1 :{
				int x = (int) p.getX() + 100;
				int y = (int) p.getY() - 200;
				Point p1 = new Point(x , y ); if(Chess.checkPoint(p1)){list.add(p1);} 		} break ;
			case 2 :{
				int x = (int) p.getX() - 100;
				int y = (int) p.getY() + 200;
				Point p1 = new Point(x , y ); if(Chess.checkPoint(p1)){list.add(p1);} 		} break ;
			case 3 :{
				int x = (int) p.getX() + 100;
				int y = (int) p.getY() + 200;
				Point p1 = new Point(x , y ); if(Chess.checkPoint(p1)){list.add(p1);} 		} break ;
			case 4 : {
				int x = (int) p.getX() - 200;
				int y = (int) p.getY() - 100;
				Point p1 = new Point(x , y ); if(Chess.checkPoint(p1)){list.add(p1);} 		} break ;
			case 5 :{
				int x = (int) p.getX() + 200;
				int y = (int) p.getY() - 100;
				Point p1 = new Point(x , y ); if(Chess.checkPoint(p1)){list.add(p1);} 		} break ;
			case 6 :{
				int x = (int) p.getX() - 200;
				int y = (int) p.getY() + 100;
				Point p1 = new Point(x , y ); if(Chess.checkPoint(p1)){list.add(p1);} 		} break ;
			case 7 :{
				int x = (int) p.getX() + 200;
				int y = (int) p.getY() + 100;
				Point p1 = new Point(x , y ); if(Chess.checkPoint(p1)){list.add(p1);} 		} break ;
			}
			
		}
		return list ;
	}

	public static Chess getChess(int color) {


		// TODO Auto-generated method stub
		HorseChess chess = new HorseChess() ;
		if(color == 1 ){
			chess.setColor(1) ;
			chess.setName("马");
		}
		else if(color == -1){
			chess.setColor(-1) ;
			chess.setName("马");
		}
		return chess;
	
	
	}
}
package ChinaChess;

import java.awt.Color;
import java.awt.Point;
import java.util.ArrayList;

public class SuperChess extends Chess{
	
	public SuperChess(){
		this.setType("Super") ;
		ArrayList<Point> allowP = new ArrayList<Point>();
		allowP.add(new Point(300 , 0));
		allowP.add(new Point(300 , 100));
		allowP.add(new Point(300 , 200));
		allowP.add(new Point(400 , 0));
		allowP.add(new Point(400 , 100));
		allowP.add(new Point(400 , 200));
		allowP.add(new Point(500 , 0));
		allowP.add(new Point(500 , 100));
		allowP.add(new Point(500 , 200));
		allowP.add(new Point(300 , 900));
		allowP.add(new Point(300 , 800));
		allowP.add(new Point(300 , 700));
		allowP.add(new Point(400 , 900));
		allowP.add(new Point(400 , 800));
		allowP.add(new Point(400 , 700));
		allowP.add(new Point(500 , 900));
		allowP.add(new Point(500 , 700));
		allowP.add(new Point(500 , 800));
		this.setAllowPoint(allowP);
	}
	@Override
	public ArrayList<Point> getNextStep() {
		// TODO Auto-generated method stub
		Point p = this.getPoint();
		ArrayList<Point> next = new ArrayList<Point>();
		int x = (int)p.getX();
		int y = (int)p.getY();
		next.add(new Point(x -MainFrame.length, y)) ;
		next.add(new Point(x +MainFrame.length, y)) ;
		next.add(new Point(x , y-MainFrame.length)) ;
		next.add(new Point(x , y+MainFrame.length)) ;
		next.retainAll(getAllowPoint());
			return next ;
		
		
	}

	public static Chess getChess(int color) {
		// TODO Auto-generated method stub
		SuperChess chess = new SuperChess() ;
		if(color == 1 ){
			chess.setColor(1) ;
			chess.setName("帅");
			chess.setPoint(new Point(400 , 0)) ;
		}
		else if(color == -1){
			chess.setColor(-1) ;
			chess.setName("将");
			chess.setPoint(new Point(400 , 900)) ;
		}
		return chess;
	}

}

下面是关于服务器端的:

package ChinaChess;

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

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;


public class ServiceMain {

	public static void main(String[] args) {

		IoAcceptor acceptor = new NioSocketAcceptor() ;
		acceptor.getSessionConfig().setReadBufferSize(2048) ;
		
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10) ; //读写通道在10秒内无任何操作进入空闲状态
		/**
		 * 过滤器,通过编解码器工厂来对字符串进行编解码处理
		 */
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf-8"),LineDelimiter.WINDOWS.getValue(),LineDelimiter.WINDOWS.getValue() )));
		/*new TextLineCodecFactory( <span style="white-space:pre"> </span>Charset.forName("UTF-8")
											<span style="white-space:pre"> </span>LineDelimeter.WINDOS.getValue(),
											<span style="white-space:pre"> </span>LineDelimeter.WINDOS.getValue()
				)*/
		/*acceptor.getFilterChain().addLast("codec",  
                new ProtocolCodecFilter(  
                        new ObjectSerializationCodecFactory()));  */
		acceptor.setHandler(new ServiceHandler()) ;
		
		try {
			acceptor.bind(new InetSocketAddress(9132));
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	
	}

}
package ChinaChess;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;

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

import tools.StringKit;



public class ServiceHandler extends  IoHandlerAdapter{
	/**
	 * 发送消息规则
	 * 01 01/02 00 00     /链接成功/失败
	 * 02 01/02 00 00 	  /匹配到对手分配为红旗/白棋
	 * 03 00 00 00	/你输了
	 * 04 00/01 00 00      直接/询问重新开始
	 * 
	 * 
	 */
	private static final Logger logger = Logger.getLogger(ServiceHandler.class);
	public static ConcurrentHashMap<String ,ArrayList<IoSession>> sessionMap = new ConcurrentHashMap<String, ArrayList<IoSession>>(); 
	public static ArrayList<IoSession> sessionList = new ArrayList<IoSession>() ;
	public static int num = 0 ;
	public void sessionOpened(IoSession session )throws Exception{
		
		logger.info("Open") ;
	}
	@Override
    public void exceptionCaught(IoSession session, Throwable cause)
	    throws Exception {
	if (!(cause instanceof IOException)) {
	    cause.printStackTrace();
	}
    }
	@Override
	public void  messageSent(IoSession session, Object message)throws Exception{
		logger.info("发送的消息:"+message.toString() + session.getRemoteAddress());
		
	}
	@Override
	public void messageReceived(IoSession session, Object message)throws Exception{
		String ip = session.getRemoteAddress().toString().substring(1 ,session.getRemoteAddress().toString().indexOf(":") ) ;
		String[] str = StringKit.separate((String)message, " ");
		
		for(String key : sessionMap.keySet()){
			if( key.indexOf(ip)>=0 ){
				ArrayList<IoSession> list = sessionMap.get(key);
				if(str[0].equals("04") && str[1].equals("00")){
					int num = 1 ;
					for(IoSession se : list){
						se.write("02 0"+num+" 00 00") ;
						num++ ;
					}
				}
				
				for(IoSession se : list){
					String seIp = se.getRemoteAddress().toString().substring(1 ,se.getRemoteAddress().toString().indexOf(":") ) ;
					if(!seIp.equals(ip)){
						se.write((String)message);
					}
				}
			}
		}
	}
	@Override
	public void sessionCreated(IoSession session) throws Exception{
		String ip = session.getRemoteAddress().toString().substring(1 ,session.getRemoteAddress().toString().indexOf(":") ) ;
		logger.info(ip+" 已连接") ;
		session.write("01 01 00 00") ;
		if(sessionList != null && sessionList.size() > 0 ){
			IoSession getSession = sessionList.get(0);
			String getIp = getSession.getRemoteAddress().toString().substring(1 ,getSession.getRemoteAddress().toString().indexOf(":") ) ;
			String Name = createFileName(ip, getIp);
			ArrayList<IoSession> list = new ArrayList<IoSession>();
			list.add(session);
			list.add(getSession);
			session.write("02 01 00 00") ;
			getSession.write("02 02 00 00") ;
			sessionList.remove(getSession);
			sessionMap.put(Name, list) ;
		}
		else{
			if(sessionList == null ){
				sessionList = new ArrayList<IoSession>();
			}
			sessionList.add(session);
		}
	}
	@Override
	public void sessionClosed(IoSession session){
		String ip = session.getRemoteAddress().toString().substring(1 ,session.getRemoteAddress().toString().indexOf(":") ) ;
		logger.info(ip+" 已退出") ;
		session.write("01 02 00 00") ;
		for(String key : sessionMap.keySet()){
			if(key.indexOf(ip) >= 0){
				ArrayList<IoSession> list = sessionMap.get(key);
				for(IoSession getSession : list){
					String getip = getSession.getRemoteAddress().toString().substring(1 ,getSession.getRemoteAddress().toString().indexOf(":") ) ;
					if(!getip.equals(ip)){
						sessionList.add(getSession);
						getSession.write("01 01 00 00") ;
					}
				}
				sessionMap.remove(key);
			}
		}
	}
	public static String createFileName(String sender , String receiver){
		/*String send = sender.replace(".", "_") ;
		String receiv = receiver.replace(".", "_") ;*/
		ArrayList<String> list = new ArrayList<String>();
		list.add(sender) ;
		list.add(receiver) ;
		Collections.sort(list) ;
		
		return list.get(0)+"&"+list.get(1) ;
	}
	public static void main(String[] args) {
		
	}

}

猜你喜欢

转载自dwj147258.iteye.com/blog/2293903