Strumenti Utente

Strumenti Sito


lpr-b-2007-2008:remotepacket
package nfs;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.DatagramPacket;
 
public class RemotePacket {
 
	public final static int MAXPACKET = 1024;
 
	String op = null;
	String [] args = null;
	DatagramPacket dp = null; 
 
	public static DatagramPacket RemotePacket(String op, String ... params) {
		/* creates a datagram packet given a number of parameters
		 */
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		PrintStream ps = new PrintStream(baos);
		// print the operation type
		ps.println(op);
		// print the lenght of byte involved
		ps.println(params.length);
		// print the parameters
		for(int i=0; i<params.length; i++)
			ps.println(params[i]);
		ps.println("ENDPACKET");
		ps.flush();
		byte [] buffer = baos.toByteArray();
		DatagramPacket dp1 = new DatagramPacket(buffer, 0, buffer.length);
		return dp1;
	}
 
	public RemotePacket(DatagramPacket dp) {
		/* building of a remote packet from a datagram packet by separating
		 * - the operation requested (READ, WRITE, OPEN, CLOSE)
		 * - the arguments related to the operation (filenames, handlers, etc.)
		 * */
		try {
			this.dp = dp;
			byte [] buffer = dp.getData();
			ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
			BufferedReader br = new BufferedReader(new InputStreamReader(bais));
			/*arguments of the command line are separated by \n*/
			this.op = br.readLine();
			int numargs = Integer.parseInt(br.readLine());
			if(numargs>0) {
				this.args = new String[numargs];
				for(int i=0; i<numargs; i++) {
					this.args[i] = br.readLine();
				}
			}
		} catch(IOException e) {
			e.printStackTrace();
		}
		return;
	}
 
	public String getOp() {
		return op;
	}
 
	public String [] getArgs() {
		return args;
	}
 
	public String toString() {
		String s = op+"::";
		for(int i=0;i<args.length;i++)
			s = s+" "+args[i];
		return s;
	}
}
lpr-b-2007-2008/remotepacket.txt · Ultima modifica: 19/09/2008 alle 14:08 (11 anni fa) (modifica esterna)