All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.tom.protocol.str.StringAdaptor Maven / Gradle / Ivy

The newest version!
package cn.tom.protocol.str;


import java.io.IOException;
import java.net.SocketAddress;

import cn.tom.kit.IoBuffer;
import cn.tom.transport.IoAdaptor;
import cn.tom.transport.Session;
import cn.tom.transport.Ticket;
import cn.tom.transport.TicketManager;
import cn.tom.transport.udp.UdpSession;
import cn.tom.transport.Messager.MessageCallback;

public class StringAdaptor extends IoAdaptor { 
	public StringAdaptor() {
	}
	
	@Override
	public IoBuffer encode(StrMsg msg, Session session) { 
		return msg.toBytes(); 
	}
    
	@Override
	public StrMsg decode(IoBuffer buf, Session session) {  
		if(buf.remaining() < 12) return null;
		buf.markReadIndex();
		int len = buf.readInt();
		if(buf.remaining() < len){
			buf.resetReadIndex();
			return null;
		}
		long id =  buf.readLong();
		String msg = new String (buf.readBytes(len-8));
		StrMsg msg2 = new StrMsg(msg);
		msg2.id = id;
		return msg2;
	}

	@Override
	public void onMessage(StrMsg msg, Session sess) throws IOException {
		if(sess.isServer()){
			sess.write(msg);
		}else{
			if (msg.getMsgId() == null || msg.getMsgId().isEmpty()) {
				return;
			}
			Ticket ticket = removeTicket(msg.getMsgId());
			if (ticket != null) { // 此种情况为 ResultCallback 为null
				ticket.notifyResponse(msg);
			}else{
				System.out.println("drop message");
			}
		}
	}
	
	@Override
	public void onMessage(StrMsg msg, Session sess, SocketAddress address) throws IOException {
		UdpSession usess = (UdpSession) sess;
		if(sess.isServer()){
			usess.write(msg, address);
		}else{
			if (msg.getMsgId() == null || msg.getMsgId().isEmpty()) {
				return;
			}
			Ticket ticket = removeTicket(msg.getMsgId());
			if (ticket != null) { // 此种情况为 ResultCallback 为null
				ticket.notifyResponse(msg);
			}else{
				System.out.println("drop message");
			}
		}
	
	}
	
	


	@Override
	public void heartbeat(Session sess) {
		if(sess.isServer()) return;
		// TODO 定时发送心跳
	}

	@Override
	public Ticket createTicket(StrMsg req, long timeout, MessageCallback callback) {
		return TicketManager.get().createTicket(req, timeout, callback);
	}

	@Override
	public Ticket removeTicket(String id) {
		return TicketManager.get().removeTicket(id);
	}


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy