`
fly_hyp
  • 浏览: 295769 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

用mina写了一个Memcache服务端的通讯模拟程序

    博客分类:
  • Java
阅读更多
我用mina写了一个Memcache服务端的通讯模拟程序
使用的是 mina-core-2.0.0-M1.jar
一共3各类
HypTestServerHandler
MinaUtilRun 启动类
TimeServerHandler

欢迎和我交流着方面的问题。


public class TimeServerHandler extends IoHandlerAdapter {
	public void exceptionCaught(IoSession session, Throwable t)
			throws Exception { // 出现异常的时候调用.
		t.printStackTrace();
		session.close();
	}

	public void messageReceived(IoSession session, Object msg) throws Exception { // 接收客户端新的消息的时候调用.
		String str = msg.toString();
		if (str.trim().equalsIgnoreCase("quit")) {
			session.close();
			return;
		}

		Date date = new Date();
		session.write(date.toString());
		System.out.println("Message written...");
	}

	public void sessionCreated(IoSession session) throws Exception { // 当一个客户端连接到服务器的时候被调用.
		System.out.println("Session created...");

		if (session.getTransportType() == TransportType.SOCKET)
			((SocketSessionConfig) session.getConfig())
					.setReceiveBufferSize(2048);

		session.setIdleTime(IdleStatus.BOTH_IDLE, 10);
	}
}


public class MinaUtilRun {
	
	private static final int PORT = 11211;

    public static void test() throws Exception {
    	
        ByteBuffer.setUseDirectBuffers(false);
        ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

        IoAcceptor acceptor = new SocketAcceptor();

        SocketAcceptorConfig cfg = new SocketAcceptorConfig(); //创建一个与SocketAcceptor相关联的配置对象.
        cfg.getSessionConfig().setReuseAddress( true );
        cfg.getFilterChain().addLast( "logger", new LoggingFilter() );
        cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new HypLineCodecFactory( Charset.forName( "GBK" ))));

        //acceptor.bind( new InetSocketAddress(PORT), new TimeServerHandler(), cfg);//绑定端口,处理对象和配置对象.
        acceptor.bind( new InetSocketAddress(PORT), new HypTestServerHandler(), cfg);//绑定端口,处理对象和配置对象.
        
        System.out.println("MINA Time server started.");
        
    }

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			test();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


public class HypTestServerHandler extends IoHandlerAdapter {
	public void exceptionCaught(IoSession session, Throwable t)
			throws Exception { // 出现异常的时候调用.
		t.printStackTrace();
		session.close();
	}

	public void messageReceived(IoSession session, Object msg) throws Exception { // 接收客户端新的消息的时候调用.
		String stat = (String) session.getAttribute("stat");
		String str = msg.toString();
		JavaUtil.debugPrint("receive:" + str);
		if(stat.equals("GetCommand")){
			if(str.equals("version")){
				session.write("VERSION 1.2.2");
				JavaUtil.debugPrint("response verison .... VERSION 1.2.2");
				return;
			}	
			if(str.startsWith("set ")){
				String[] parts = str.split(" ");
				int dataSize = Integer.parseInt(parts[4]);
				JavaUtil.debugPrint("dataSize:" + dataSize);
				session.setAttribute("dataSize", dataSize);
				session.setAttribute("readSize", 0);
				session.setAttribute("stat", "readData");
				session.setAttribute("dataBuf", new StringBuilder());
				session.setAttribute("currentCmd", parts);
			}
		}else if(stat.equals("readData")){
			int dataSize = (Integer)session.getAttribute("dataSize");
			int readSize = (Integer)session.getAttribute("readSize");
			StringBuilder buf = (StringBuilder)session.getAttribute("dataBuf");
			if(buf.length() > 0){
				buf.append("\r\n");
			}
			buf.append(str);
			readSize += str.length() + 2;
			session.setAttribute("readSize", readSize);
			JavaUtil.debugPrint("read data:" + readSize + "/" +dataSize );
			if(readSize == dataSize){
				//处理命令
				String[] parts = (String[])session.getAttribute("currentCmd");				
				System.out.println("buf.length():" + buf.length());
				System.out.println(buf.toString());
				session.write("STORED");				
				session.setAttribute("stat", "GetCommand");
				}
		}
		
		
		
		
			
		

		//Date date = new Date();
		//session.write(date.toString());
		System.out.println("Message written...");
	}

	public void sessionCreated(IoSession session) throws Exception { // 当一个客户端连接到服务器的时候被调用.
		System.out.println("Session created...");

		if (session.getTransportType() == TransportType.SOCKET)
			((SocketSessionConfig) session.getConfig())
					.setReceiveBufferSize(2048);

		session.setIdleTime(IdleStatus.BOTH_IDLE, 10);
		session.setAttribute("stat", "GetCommand");
	}
}



4
1
分享到:
评论
2 楼 fly_hyp 2010-01-03  
xianglei 写道
new HypLineCodecFactory( Charset.forName( "GBK" ))) HypLineCodecFactory这个类呢?

就是下面这些代码吧!
/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
//这是从Mina的源代码摘过来的
package cn.sh.flyhyp.memcache.client.codec;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

/**
 * A delimiter which is appended to the end of a text line, such as
 * <tt>CR/LF</tt>.
 *
 * @author The Apache MINA Project (dev@mina.apache.org)
 * @version $Rev: 714210 $, $Date: 2009-05-06 06:47:16 $
 */
public class LineDelimiter {
    /**
     * the line delimiter constant of the current O/S.
     */
    public static final LineDelimiter DEFAULT;

    static {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        PrintWriter out = new PrintWriter(bout);
        out.println();
        DEFAULT = new LineDelimiter(new String(bout.toByteArray()));
    }

    /**
     * A special line delimiter which is used for auto-detection of
     * EOL in {@link MemcachedDecoder}.  If this delimiter is used,
     * {@link MemcachedDecoder} will consider both  <tt>'\r'</tt> and
     * <tt>'\n'</tt> as a delimiter.
     */
    public static final LineDelimiter AUTO = new LineDelimiter("");

    /**
     * The CRLF line delimiter constant (<tt>"\r\n"</tt>)
     */
    public static final LineDelimiter CRLF = new LineDelimiter("\r\n");
        
    /**
     * The line delimiter constant of UNIX (<tt>"\n"</tt>)
     */
    public static final LineDelimiter UNIX = new LineDelimiter("\n");

    /**
     * The line delimiter constant of MS Windows/DOS (<tt>"\r\n"</tt>)
     */
    public static final LineDelimiter WINDOWS = CRLF;

    /**
     * The line delimiter constant of Mac OS (<tt>"\r"</tt>)
     */
    public static final LineDelimiter MAC = new LineDelimiter("\r");

    /**
     * The line delimiter constant for NUL-terminated text protocols
     * such as Flash XML socket (<tt>"\0"</tt>)
     */
    public static final LineDelimiter NUL = new LineDelimiter("\0");

    private final String value;

    /**
     * Creates a new line delimiter with the specified <tt>value</tt>.
     */
    public LineDelimiter(String value) {
        if (value == null) {
            throw new NullPointerException("delimiter");
        }
        this.value = value;
    }

    /**
     * Return the delimiter string.
     */
    public String getValue() {
        return value;
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof LineDelimiter)) {
            return false;
        }

        LineDelimiter that = (LineDelimiter) o;
        return this.value.equals(that.value);
    }

    @Override
    public String toString() {
        StringBuffer buf = new StringBuffer();
        buf.append("delimiter:");
        if (value.length() == 0) {
            buf.append(" auto");
        } else {
            for (int i = 0; i < value.length(); i++) {
                buf.append(" 0x");
                buf.append(Integer.toHexString(value.charAt(i)));
            }
        }
        return buf.toString();
    }
}

1 楼 xianglei 2010-01-03  
new HypLineCodecFactory( Charset.forName( "GBK" ))) HypLineCodecFactory这个类呢?

相关推荐

Global site tag (gtag.js) - Google Analytics