view rep/REPPacketReceive.java @ 21:2d4bab638a71

*** empty log message ***
author pin
date Thu, 08 Nov 2007 04:37:59 +0900
parents 83088d943612
children 2d51078d94dd
line wrap: on
line source

package rep;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.StringTokenizer;

public class REPPacketReceive {
	
	SocketChannel socketchannel;
	private final int HEADER_SIZE = 24;
	//private String host;
	//private int port;
	
	public REPPacketReceive(SocketChannel sc){
		socketchannel = sc;
	}

	
	public REPCommand unpack() {

		ByteBuffer header = ByteBuffer.allocateDirect(HEADER_SIZE);
		long len = 0;
		header.clear();
		try {
			len = socketchannel.read(header);
			if(len == -1){
				socketchannel.close();
				return null;
			}else if(len == 0){
				return null;
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}  // limit = read length
		if (len !=HEADER_SIZE) {
			System.out.println("‚Ä‚·");
			// this can't happen
		}
		header.rewind();  // position = 0

		String text = "";
		int cmd = header.getInt();
		int sid = header.getInt();
		int eid = header.getInt();
		int seqid = header.getInt();
		int lineno = header.getInt();
		int textsiz = header.getInt()/2;
		
		ByteBuffer textBuffer = ByteBuffer.allocateDirect(textsiz*2);

		try {
			len = socketchannel.read(textBuffer);
		} catch (IOException e1) {
			e1.printStackTrace();
		}  // limit = read length
		if (len != textsiz * 2) {
			// this can't happen
			System.out.println("‚ ‚Æ");
		}
		textBuffer.rewind();
		for(int i=0;i<textsiz;i++) {
			text +=textBuffer.getChar();
		}
		String string = text;
		//System.out.println(string);
		//getSocket(string);
		REPCommand repcommand = new REPCommand(cmd, sid, eid, seqid, lineno, textsiz, string);
		System.out.println("received command: " + repcommand.toString());
		//getSocket(repcommand);
		//System.out.println("received command: " + repcommand.toString());
		return repcommand;
	}


	private void getSocket(REPCommand command) {
		if(command.cmd != REP.SMCMD_JOIN){
		String string = command.string;
		StringTokenizer st2 = new StringTokenizer(string, ":");
		LinkedList<String> list = new LinkedList<String>();
		while (st2.hasMoreTokens()){
			list.add(st2.nextToken());
		}
		String port = list.getLast();
		list.removeLast();
		String host = list.getLast();
		int socketInfoLength = host.length() + port.length() + 2;
		System.out.println(host.length() + ":" + port.length() + ":" + socketInfoLength);
		command.setString(string.substring(0, string.length() - socketInfoLength));
		command.setHost(host);
		command.setPort(port);
		}
	}
}