Results 1 to 6 of 6

Thread: UDP FTP Server

  1. #1
    Java101 is offline Member
    Join Date
    Jan 2012
    Posts
    8
    Rep Power
    0

    Default UDP FTP Server

    Hi,

    I'm writing an FTP client and server using UDP,

    Java Code:
    import java.io.*;
    import java.net.*;
    import java.util.HashMap;
    
    public class FileServer {
    
    	static HashMap<String, byte[]> files = new HashMap<String, byte[]>();
    
    	public static void main (String args[]) throws IOException, ClassNotFoundException  {
    		int portNum = 5000;
    		int timeout = 2000; //in milliseconds
    		DatagramSocket sock = new DatagramSocket(portNum);
    		final int PACKET_SIZE = 1024;
    		
    	    System.out.println("FileServer Online");
    		byte[] rxBuff = new byte[PACKET_SIZE];
    		byte[] txBuff = new byte[PACKET_SIZE];
    
    		ByteArrayInputStream bais;
    		ObjectInputStream ois;
    		ByteArrayOutputStream baos = new ByteArrayOutputStream(PACKET_SIZE);
    		ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(baos));
    		oos.flush();
    		
    		while(true) {
    			
    			System.out.println("Waiting for Requests...");
    			
    			// Wait for requests
    			DatagramPacket reqPacket = new DatagramPacket(rxBuff, rxBuff.length );
    			sock.receive(reqPacket);	
    			System.out.println("Request received... IP: " + reqPacket.getAddress());	
    			
    			bais = new ByteArrayInputStream(rxBuff);
    			ois = new ObjectInputStream(bais);
    			
    			FileRequest fr = (FileRequest) ois.readObject();
    			System.out.println(fr.filename + " " + fr.direction + "load requested...");	
    			
    			
    			// Send ack when req received
    			Acknowledgement ack = new Acknowledgement(fr.getSeqNum());
    			oos.writeObject(ack);
    			oos.flush();
    			
    			txBuff = baos.toByteArray();
    			DatagramPacket ackPacket = new DatagramPacket(txBuff, txBuff.length, reqPacket.getAddress(), reqPacket.getPort() );
    			
    			sock.setSoTimeout(timeout);
    			boolean reqAcksent = false;
    			while (reqAcksent == false) {
    				try {
    					sock.send(ackPacket);
    					reqAcksent = true;
    					System.out.println(fr.getSeqNum() + " acknowledgement sent...");
    				} catch (SocketTimeoutException e) {
    					e.printStackTrace();
    				}
    			}
    			sock.setSoTimeout(0);
    	
    			if (fr.direction.equals("up")) {
    				//Receive data
    				DatagramPacket dataFromClient = new DatagramPacket(rxBuff, rxBuff.length );
    				
    				sock.receive(dataFromClient);
    				try {
    					FileData fd = (FileData) ois.readObject();
    					files.put(fr.filename, fd.getData());
    					System.out.println(fr.filename + " uploaded...");
    				} catch (StreamCorruptedException e) {
    				} finally {// Send ack when data received
    					ack = new Acknowledgement(1111);//fd.getSeqNum());
    					oos.writeObject(ack);
    					oos.flush();
    					
    					txBuff = baos.toByteArray();
    					ackPacket = new DatagramPacket(txBuff, txBuff.length, reqPacket.getAddress(), reqPacket.getPort() );
    					
    					sock.send(ackPacket);
    					System.out.println(/*fd.getSeqNum() +*/ " acknowledgement sent...");
    				}
    
    	
    			}
    			else if (fr.direction.equals("down")) {
    				// Send data
    				//wait for ack
    				FileData fdToClient = new FileData(PACKET_SIZE, files.get(fr.filename));
    				oos.writeObject(fdToClient);
    				oos.flush();
    				
    				txBuff = baos.toByteArray();
    				DatagramPacket dataToClient = new DatagramPacket(txBuff, txBuff.length, reqPacket.getAddress(), reqPacket.getPort() );
    				
    				sock.send(dataToClient);
    				System.out.println(fr.filename + " sent...");
    
    				// Receive ack when data sent
    				ackPacket = new DatagramPacket(rxBuff, rxBuff.length, reqPacket.getAddress(), reqPacket.getPort() );
    				sock.receive(ackPacket);
    				
    				ack = (Acknowledgement) ois.readObject();
    				System.out.println(ack.getSeqNum() + " Ack received...");
    				
    			}
    			
    			System.out.println("Files on server: " + FileServer.files.toString());
    			
    		}
    	}
    }
    The problem lies on the file server when uploading or direction = up,
    I keep getting the following exception from line 68:
    java.io.StreamCorruptedException: invalid type code: 00.

    Here is the client:
    Java Code:
    import java.io.*;
    import java.net.*;
    
    public class Client {
    	
        private static int portNum = 5000; 
    	private static DatagramSocket sock;
    	private static InetAddress server;
    	static int timeout = 2000; //in milliseconds
    	public final static int PACKET_SIZE = 1024;
    	
    	private static Acknowledgement ack;
    	
    	private static ByteArrayInputStream bais;
    	private static ObjectInputStream ois;
    	private static ByteArrayOutputStream baos;
    	private static ObjectOutputStream oos;
    	
    	static boolean validArgs = false;
    	
    	public static void main(String args[]) throws IOException, ClassNotFoundException {
    		
    		String direction = "up";
    		//String direction = "down";
    		String filename = "test1.txt";
    		int blocksize = 8;
    		/******************
    		String direction = args[0];
    		String filename = args[1];
    		int blocksize = Integer.parseInt(args[2]); 
    		*******************/
    		
    		if ( direction.equals("up") && (blocksize > 0) ) {
    			File file = new File (filename);
    			if (!file.exists()) {
    				System.out.println("Args Error: file does not exist");
    			}
    			else if (blocksize <= file.length()) {
    				 validArgs = true;
    			} else {
    				 System.out.println("Args Error: blocksize (" + blocksize + ") greater than filesize (" + file.length() + ")");				
    			}
    		} else if ( direction.equals("down") && blocksize > 0 ) {
    			 validArgs = true;			
    		} else {
    			 validArgs = false;	
    			 System.out.println("Args Error: invalid direction or negative blocksize");
    		}
    		
    		if (validArgs) {
    			server = InetAddress.getByName("localhost");
    			sock = new DatagramSocket();
    			sock.setSoTimeout(timeout);
    			System.out.println("Connection to server established");
    			
    			byte[] rxBuff = new byte[PACKET_SIZE];	//holds datagram packets
    			byte[] txBuff = new byte[PACKET_SIZE];
    			
    			
    			/**Create File request, convert to byte[] and fill txBuff**/
    			baos = new ByteArrayOutputStream(PACKET_SIZE);
    			oos = new ObjectOutputStream(new BufferedOutputStream(baos));
    			FileRequest fr = new FileRequest(filename, direction);
    			oos.writeObject(fr);
    			oos.flush();
    			txBuff = baos.toByteArray();
    			
    			DatagramPacket reqPacket = new DatagramPacket(txBuff, txBuff.length, server, portNum ); //holds request packets
    			DatagramPacket ackPacket = new DatagramPacket(rxBuff, rxBuff.length, server, portNum ); //holds acknowledgement packets
    			DatagramPacket fdPacket = new DatagramPacket(txBuff, txBuff.length, server, portNum );  //holds file data packets
    			
    			/**Send request, if reply not received within 2 seconds, resend**/
    			boolean requestSent = false;
    			while (requestSent == false) {
    				try {
    					sock.send(reqPacket);
    					System.out.println(fr.getSeqNum() + "PID: Request sent...");
    					
    					sock.receive(ackPacket);
    					
    					bais = new ByteArrayInputStream(rxBuff);
    					ois = new ObjectInputStream(bais);
    					
    					ack = (Acknowledgement) ois.readObject();
    					requestSent = true;
    					System.out.println(ack.getSeqNum() + "PID: Request Ack received...");
    
    				} catch (SocketTimeoutException e) {
    					e.printStackTrace();
    				}
    			}
    
    			if (direction.equals("up")) {
    			    byte[] fileByteArray = new byte[blocksize];
    		    	try {
    			        FileInputStream fis = new FileInputStream(filename);
    			        BufferedInputStream bis = new BufferedInputStream(fis);
    			        bis.read(fileByteArray,0,fileByteArray.length);
    		    	} catch (FileNotFoundException e) {
    		    		System.out.println("Client Error: File not found");
    		    	} catch (IOException e) {
    		    		System.out.println(e.getMessage());    		
    		    	}
    				
    				FileData fd = new FileData(blocksize, fileByteArray);
    				oos.writeObject(fd);
    				oos.flush();
    				txBuff = baos.toByteArray();
    
    				/**Send data, if reply not received within 2 seconds, resend**/
    				boolean dataSent = false;
    				while (dataSent == false) {
    					try {
    						sock.send(fdPacket);
    						System.out.println(fd.getSeqNum() + "PID: " + filename + " sent...");
    						
    						sock.receive(ackPacket);
    		
    						bais = new ByteArrayInputStream(rxBuff);
    						ois = new ObjectInputStream(bais);						
    						ack = (Acknowledgement) ois.readObject();
    						dataSent = true;
    						System.out.println(ack.getSeqNum() + "PID: Data Ack received...");
    
    					} catch (SocketTimeoutException e) {
    						e.printStackTrace();
    					}
    				}
    			}
    		    else if (direction.equals("down")) {
    
    				File file = new File (filename);	
    		        FileOutputStream fos = new FileOutputStream(file);
    		        BufferedOutputStream bos = new BufferedOutputStream(fos);
    		        
    		    	/***Receive data***/
    				DatagramPacket dataFromClient = new DatagramPacket(rxBuff, rxBuff.length );
    				
    				sock.receive(dataFromClient);
    				FileData fd = (FileData) ois.readObject();
    				
    				try {
    			        bos.write(fd.getData(),0,fd.getData().length);
    					bos.close();
    		        } catch (IOException e) {
    		    		System.out.println(e.getMessage());
    					bos.close();
    					file.delete();
    		        }
    
    				System.out.println(filename + " downloaded...");
    						
    				/***Send ack when data received***/
    				//Create ack and write to buffer
    				ack = new Acknowledgement(fd.getSeqNum());
    				oos.writeObject(ack);
    				oos.flush();
    				
    				//make packet with buffer
    				txBuff = baos.toByteArray();
    				ackPacket = new DatagramPacket(txBuff, txBuff.length, reqPacket.getAddress(), reqPacket.getPort() );
    				
    				//send packet
    				sock.send(ackPacket);
    				System.out.println(fr.getSeqNum() + " acknowledgement sent...");	
    		    }
    		}	
    		sock.close();
    	}
    }
    Any help would be greatly appreciated!

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,331
    Rep Power
    25

    Default Re: UDP FTP Server

    The posted code will not compile because there are several missing classes .

  3. #3
    Java101 is offline Member
    Join Date
    Jan 2012
    Posts
    8
    Rep Power
    0

    Default Re: UDP FTP Server

    Apologies!

    Here are the missing classes:

    Java Code:
    import java.io.Serializable;
    
    
    @SuppressWarnings("serial")
    public class Acknowledgement implements Serializable {
    	private long seqNum;
    	
    	public Acknowledgement (long sn) {
    		this.seqNum = sn;
    	}
    	
    	public long getSeqNum() {
    		return seqNum;
    	}
    }

    Java Code:
    import java.io.Serializable;
    
    
    @SuppressWarnings("serial")
    public class FileData implements Serializable {
    	private long seqNum;
    	private long ackNum;
    	private int chunkSize;
    	private byte[] data;
    	
    	public FileData (int chunk, byte[] data) {
    		this.seqNum = System.currentTimeMillis();
    		this.ackNum = 0; 
    		this.chunkSize = chunk;
    		this.data = data;
    	}
    	
    	public long getSeqNum () {
    		return seqNum;
    	}
    	
    	public void setSeqNum (long sn) {
    		this.seqNum = sn;
    	}
    	
    	public long getAckNum () {
    		return ackNum;
    	}
    	
    	public void setAckNum (long an) {
    		ackNum = an;
    	}
    	
    	public int getChunkSize () {
    		return chunkSize;
    	}
    	
    	public void setChunkSize (int cs) {
    		chunkSize = cs;
    	}
    	
    	public byte[] getData () {
    		return data;
    	}
    	
    	public void setData (byte[] d) {
    		this.data = d;
    	}
    }
    Java Code:
    import java.io.Serializable;
    
    @SuppressWarnings("serial")
    public class FileRequest implements Serializable {
    
    	private long seqNum;
    	private long ackNum;
    	public String filename; //file being transferred
    	public String direction; //"up" or "down" are valid values for this
    
    	
    	public FileRequest (String fn, String dir) {
    		this.seqNum = System.currentTimeMillis();
    		this.ackNum = 0;
    		this.filename = fn;
    		this.direction = dir;
    	}
    
    	public long getSeqNum () {
    		return seqNum;
    	}
    	
    	public void setSeqNum (long sn) {
    		this.seqNum = sn;
    	}
    	
    	public long getAckNum () {
    		return ackNum;
    	}
    	
    	public void setAckNum (long an) {
    		ackNum = an;
    	}
    
    }

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,331
    Rep Power
    25

    Default Re: UDP FTP Server

    Please post the console output for when the program executes. This is the console I get:
    Running: F:\Java\jre6\bin\java.exe -classpath D:\JavaDevelopment;.;..\. -Xmx512M FTP_Via_UDP

    FileServer Online
    Waiting for Requests...
    Connection to server established
    Request received... IP: /127.0.0.1
    FTP_TestFile.txt upload requested...
    1330991326968PID: Request sent...
    1330991326968 acknowledgement sent...
    1330991326968PID: Request Ack received...
    1330991327015PID: FTP_TestFile.txt sent...
    acknowledgement sent...
    Files on server: {}
    1330991326968PID: Data Ack received...
    Waiting for Requests...

    0 error(s)

  5. #5
    jhan is offline Member
    Join Date
    Dec 2012
    Posts
    2
    Rep Power
    0

    Default Re: UDP FTP Server

    this posted code not work !!!
    What is the solution .

  6. #6
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default Re: UDP FTP Server

    Quote Originally Posted by jhan View Post
    this posted code not work !!!
    What is the solution .
    You posted once in this thread and your post was moved to a new thread, where you have received responses: UDP FTP Server

    Please go through the Forum Rules, particularly the second paragraph.

    Any more multiple posting of the same question and you are liable to be banned for a period.

    db

    THREAD CLOSED
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. Replies: 6
    Last Post: 12-25-2011, 11:33 PM
  2. from local server to remote server
    By IDH in forum Java Servlet
    Replies: 1
    Last Post: 03-24-2011, 09:05 AM
  3. Ping a server when server is not in the localhost..
    By kshitiz in forum New To Java
    Replies: 1
    Last Post: 03-19-2009, 09:17 PM
  4. smtp server configuration with jboss server
    By vilas_patil in forum Java Servlet
    Replies: 0
    Last Post: 01-05-2009, 01:18 PM
  5. Does any file in an FTP server ends up in an HTTP server?
    By islamfunny in forum CLDC and MIDP
    Replies: 4
    Last Post: 08-15-2008, 04:30 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •