view src/remoteeditor/network/REPPacketReceive.java @ 34:7d80c9318695

*** empty log message ***
author pin
date Wed, 31 Jan 2007 02:06:52 +0900
parents
children 0c5701885b09
line wrap: on
line source

package remoteeditor.network;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import remoteeditor.command.REPCommand;
import remoteeditor.command.REPCommandEvent;
import remoteeditor.command.REPCommandListener;

public class REPPacketReceive implements Runnable{
	
	SocketChannel socketchannel;
	private int HEADER_SIZE = 24;
	private REPCommandListener commandlistener;
	
	public REPPacketReceive(SocketChannel sc){
		socketchannel = sc;
	}

	
	public REPCommand unpack() {
		System.out.println("test1");
		ByteBuffer header = ByteBuffer.allocateDirect(HEADER_SIZE);
		long len = 0;
		header.clear();
		try {
			len = socketchannel.read(header);
		} 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);
		REPCommand repcommand = new REPCommand(cmd, sid, eid, seqid, lineno, textsiz, string);
		System.out.println(repcommand.toString());
		return repcommand;
	}
	
	public void addCommandListener(REPCommandListener listener){
		commandlistener = listener;
		Thread th = new Thread(this);
		th.start();
	}

	public void run() {
		while(socketchannel.isConnected()){
			//unpack();
			commandlistener.CommandReceived(new REPCommandEvent(unpack()));
		}
	}
	
}