Hi everyone...
i am currently doing a java system concerning file transfers between server and client... file transfer starts from the server.. So far, i have done one file transfer. However, i would like to program my code in such a way that the client actively still listens to the server after a single file transfer.. also i need the client to run the files it receives in an array form. Its my final year project and i was hoping to get some help for my code. Please help as i would really appreciate it...=) Thank you in advance...=)

Here is my client code:

import java.io.* ;
import java.net.* ;
import java.util.* ;
import java.lang.*;

//import javax.swing.* ;

/*
 * Charity.java is the client-side implementation of the Prototype project, the purpose of which is to encourage
 * further understanding of the processes, methods and steps involved in making a network-capable program. It also
 * serves to clarify existing knowledge of the primitive datatype sizes and how Java deals with signed bytes in
 * networked applications (such as the raw IP address byte array in InetAddress).
 *
 * The program will query the user as to which IP address the user wants to deliver UDP packets. Only pcs with the
 * server-side implementation Goodwill.java running will reply to this packet. It sends a packet to a specified IP
 * at port 4445, the content of which is empty (carries only 256 bytes of uninitialized data). It will then
 * wait for a reply and print out its contents in a string.
 *
 * Run this program as "Run File". Both the server and the client programs have their own main method which will
 * conflict if "Run Project" is selected.
 *
 */

class Emissary
{
	public static void main (String args []) throws IOException
	{
		byte iptargetpc[] = new byte[4] ;
		iptargetpc[0] = -64 ;
		iptargetpc[1] = -88 ;
		iptargetpc[2] = 1 ;
		iptargetpc[3] = 88 ;

		InetAddress targetaddr = InetAddress.getByAddress (iptargetpc) ;

		/// Client implementation

		/// Get response on unicast port 4446
		final int PORT_USED = 4446 ;
		DatagramSocket socket = new DatagramSocket (4446) ;
		DatagramPacket packet ;
		byte buffer [] = new byte [256] ;
		InetAddress server_ip;
		String file_name = null;

		while (true)
		{

		new Primaria().start() ;	/// Get response on Multicast address 230.5.5.4 port 54100

		packet = new DatagramPacket(buffer, buffer.length) ;

		System.out.print ("\nNow waiting for unicast reply... \n") ;
		socket.receive (packet) ; 	// This method blocks until it receives a packet

		/// Display response
		String received = new String (packet.getData(), 0, packet.getLength ()) ; /// String (byte[] bytes, int offset, int length)
		server_ip = packet.getAddress();

		System.out.print ("Server reply unicastly : " + received + "\n") ;

		if (received.startsWith("--COPY--") == true)
		{
			System.out.println ("The server has sent a copy command. Going into copy mode and reply ACK \n") ;
			String ack = new String("ACK") ;

			byte ack_response[] = ack.getBytes () ;

			file_name = received.substring (9);
			packet.setData (ack_response) ;
			packet.setAddress (packet.getAddress()) ;
			packet.setPort (packet.getPort()) ;

			socket.send (packet) ;

			System.out.println ("Waiting for final confirmation before going in copy mode") ;
			socket.setSoTimeout (5000) ;	// Sets the timeout for the receive command so not to wait indef
			try
			{
				socket.receive (packet) ;
				if (new String(packet.getData()).startsWith ("ACK") == true)
				{	/// Transmission mode
					System.out.println ("Confirmation confirmed. Transmit Mode active") ;
					System.out.println ("File name is '" + file_name) ;
				}
				else
					throw new SocketTimeoutException() ;
			}
			catch (SocketTimeoutException se)
			{
				System.out.println ("The server did not reply to confirmation within 5 secs, terminating mode") ;
			}

			int filesize=6022386; // filesize temporary hardcoded
		    long start = System.currentTimeMillis();
    		int bytesRead;
   			int current = 0;

   			Socket sock = new Socket(server_ip,13267);
   			System.out.println("Connecting...");

   			// receive file
   			byte [] mybytearray  = new byte [filesize];
    		InputStream is = sock.getInputStream();
    		FileOutputStream fos = new FileOutputStream("Guitar1.flv");
    		BufferedOutputStream bos = new BufferedOutputStream(fos);
    		bytesRead = is.read(mybytearray,0,mybytearray.length);
    		current = bytesRead;

    		do {

    			bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
  			    if(bytesRead >= 0)
  			    	current += bytesRead;
    		} while(bytesRead > -1);

    		bos.write(mybytearray, 0 , current);
    		bos.flush();
    		long end = System.currentTimeMillis();
    		System.out.println(end-start);
    		bos.close();
   			sock.close();
		}

		socket.close() ;

		String command = new String("cmd /c start " + file_name);
		//	Runtime run = Runtime.getRuntime();
	//	Process proc = run.exec("fyp2.ppsx");
	//	Runtime.getRuntime().exec("cmd /c start " + file_name);
		Runtime.getRuntime().exec(command);
		}
	}

}


class Primaria extends Thread
{
	private static final int BUFFER_SIZE = 256 ;
	private static final int PORT_USED = 54100 ;
	private static final byte TTL_USED = (byte) 1 ;

	byte iptargetmulti[] = new byte[4] ;

	MulticastSocket comms_socket = new MulticastSocket(PORT_USED) ;
	InetAddress multicast_inetadd ;

	public Primaria () throws IOException
	{
		this ("Multicast Listener") ;
		System.out.println ("\n\nEntering Multicast Listener Thread ") ;
	}

	public Primaria (String name) throws IOException
	{
		super (name) ;		/// super refers to the Thread class and gives it a pretty name ;

		iptargetmulti[0] = (byte) 230 ;
		iptargetmulti[1] = (byte) 5 ;
		iptargetmulti[2] = (byte) 5 ;
		iptargetmulti[3] = (byte) 4 ;
		comms_socket.setTimeToLive (TTL_USED) ;

	}

	public void run ()
	{
		byte mail_buffer[] = new byte[BUFFER_SIZE] ;
		byte buffer_to_show[] ;
		String mail_output ;
		DatagramPacket incoming_packet = new DatagramPacket (mail_buffer, mail_buffer.length) ;

		try
		{
			multicast_inetadd = InetAddress.getByAddress (iptargetmulti) ;
			comms_socket.joinGroup (multicast_inetadd) ;
			System.out.println ("\nNow waiting for multicast reply...") ;
			comms_socket.receive (incoming_packet) ;
		}
		catch (IOException m)
		{
			System.out.println ("IOException error mark 1: " + m) ;
		}

		System.out.println ("Incoming message was : " + new String (mail_buffer)) ;

		try
		{
			comms_socket.leaveGroup (multicast_inetadd) ;
			comms_socket.close () ;
		}
		catch (IOException l)
		{
			System.out.println ("An error occured while leaving the group mark 2" ) ;
		}
	}
}

Thank you again... Hoping for a reply as soon as possible...=)

PS: i have uploaded my codes

Recommended Answers

All 15 Replies

What kind of protocol do you have?
Does the client connect to the server and request a file or does the server choose what file(s) it is going to send?
If the server is going to send more than one file, does it tell the client how many files it is going to send?
How are the files delimited when they are sent? How does the client know the end of one file and the beginning of the next file?

i need the client to run the files it receives in an array form

Can you explain what "run" and what "array form" mean and how they are related?


You should call the printStackTrace() method in the catch blocks to get all of the text of the error messages.

i use UDP to send a string text message unicastly and multicastly.. However, the main task of the server is to send files, for this i use TCP. The server sends the file to client. Client does not request for the file. Actually, for now it can only send one file. Thus, there is actually no delimiters. Excuse me for not telling this in the first place. I am actually new in socket programming in java.

The process is actually suppose to be like this:

Server sends file

Clients opens application to play file (say if its ppsx file, then it open in the form of powerpoint slide show, basically using runtime() )

At the same time, client socket must be open to accept another file. Thus, after accepting the second file, the file is suppose to be played in order .. such file1 then file2 then back to file1...

PS: i am actually doin a prototype server client electronic bulletin or announcement system as my final year project... thus, client only acts as a way to open files and playing them... thus, if multiple files are sent, then they are played one by one and looped. Hope u understand what i mean...

for now, the unicast and file transfer message is diffrentiated by having a "--COPY--" string attached in front of the file name in case the client should be prepared for file transfer....

for more Info, here is my server code:

import java.io.* ;
import java.net.* ;
import java.util.* ;

/*
 * Goodwill.java is the server-side implementation of the prototype. What it does (besides a few random things) is to
 * wait for any incoming packets on port 4445, decipher the IP & port origin of that packet, and then reply using
 * pre-made words from the text file energy.txt. Incoming packets do not need to have any specific format to
 * get replies. After finishing all phrases in the txt file, the server then closes down.
 *
 * Run this program as "Run File". Both the server and the client programs have their own main method which will
 * conflict if "Run Project" is selected.
 *
 */

class Hegemony
{
	public static void main (String args[]) throws IOException
	{
		/// PRIMARY MENU START
		System.out.println ("Now accessing server code... \n\n") ;
		new Dictator().start() ;
	}

}

class Propaganda
{
	private static final int PORT_USED = 54100 ;
	private static final byte TTL_USED = (byte) 1 ;		/// Range of packets within subnet


	InetAddress multicast_inetadd ;
	MulticastSocket multicast_socket ;
	private byte iptargetmulti[] = new byte[4] ;


	public Propaganda () throws IOException
	{
		BufferedReader message_input = new BufferedReader(new InputStreamReader(System.in));
		String admin_string ;

		iptargetmulti[0] = (byte) 230 ;
		iptargetmulti[1] = (byte) 5 ;
		iptargetmulti[2] = (byte) 5 ;
		iptargetmulti[3] = (byte) 4 ;

		try
		{
			multicast_inetadd = InetAddress.getByAddress (iptargetmulti) ;
			multicast_socket = new MulticastSocket (PORT_USED) ;
		}
		catch (IOException e)
		{
			System.out.println ("Error is " + e) ;
		}

		System.out.println ("\nPlease type your message to send to the multicast group " +  multicast_inetadd.toString()) ;
		admin_string = message_input.readLine() ;
		send_multicast (admin_string) ;


	}

	private void send_multicast (String message)
	{
		byte mail[] ;
		mail = message.getBytes() ;
		DatagramPacket dp = new DatagramPacket (mail, 0, mail.length, multicast_inetadd, PORT_USED) ;
		/// DatagramPacket (bytes[], int, int, InetAddress, int) ;

		try
		{
			multicast_socket.setTimeToLive (TTL_USED) ;
			//multicast_socket.joinGroup (multicast_inetadd) ;//	NOT NEEDED FOR SENDING DATA, NECESSARY FOR RECEIVING
			multicast_socket.send (dp) ;
			//multicast_socket.leaveGroup (multicast_inetadd) ;//	NOT NEEDED FOR SENDING DATA, NECESSARY FOR RECEIVING
			multicast_socket.close () ;
		}
		catch (IOException m)
		{
			System.out.println ("Error occured while delivering multicast message : " + m) ;
			System.exit (1) ;
		}

		System.out.println ("Finished delivering : " + message) ;
	}

}

class File_Transfer
{
	private static final byte TRANSFER_FILE = 1 ;
	private static final byte LIST_FILE = 2 ;
	private static final byte EXIT = 0 ;
	private static final byte DO_NOTHING = 99 ;

	private static final int SERVER_PORT = 8070 ;
	private static final int CLIENT_PORT = 4446 ;
	private static final int TRANSFER_BUFFER = 1024 ;

	Scanner fmenu_input = new Scanner (System.in).useDelimiter("\\D+") ;
	byte fmenu_option = DO_NOTHING ;


	public File_Transfer () throws IOException
	{

		while (fmenu_option != EXIT)
		{
			System.out.println ("Would you like to see the current list of files in the current directory?") ;
			System.out.println ("1. Transfer a file       2. List files in current directory   ") ;
			System.out.println ("0. exit ") ;

			fmenu_option = fmenu_input.nextByte() ;
			switch (fmenu_option)
			{
				case TRANSFER_FILE :
					transfer_file () ;
					break ;

				case LIST_FILE :
					list_files () ;
					break ;

				case EXIT :
					return ;

				default :
					System.out.println ("\nPlease input a valid option \n") ;
					fmenu_option = DO_NOTHING ;
			}
		}

	}

	private void list_files ()
	{
		String path = "." ;
		File directory = new File (path) ;
		String file_names [] ;

		if (directory.isDirectory() == true && directory.exists() == true)
		{
			try
			{
				System.out.println ("The directory's path : " + directory.getCanonicalPath ()) ;
				file_names = directory.list() ;
				System.out.print ("Files and folders existing : \n") ;
				for (int i = 0; i < file_names.length; i++)
				{
					System.out.print (file_names[i] + " \n ") ;
					if (i % 4 == 0 && i != 0)
						System.out.print ("\n") ;
				}

				System.out.print ("\n\n ") ;
			}
			catch (IOException e)
			{
				System.out.println ("The filesystem refuses to cooperate with queries. Error : " + e.getMessage ()) ;
			}

		}
	}

	private void transfer_file () throws IOException
	{
		BufferedReader name_input = new BufferedReader(new InputStreamReader(System.in));
		String file_name = null ;

		try
		{

			System.out.println ("Please specify file name (case-sensitive) : ") ;
			file_name = name_input.readLine() ;
			System.out.println ("You've typed '" + file_name + "' ") ;

			File file_to_copy = new File (file_name) ;
			if (file_to_copy.exists() == false || file_to_copy.isFile() == false)
			{
				System.out.println ("This file does not exist or is not a file") ;
				throw new IOException() ;
			}

			System.out.println ("Size of file (in bytes) : " + file_to_copy.length ()) ;
		}
		catch (IOException m)
		{
			System.out.println ("An unknown error has occured : " + m.getMessage ()) ;
			return ;
		}

		System.out.println ("Please state target ip address : ") ;
		byte ip_byte[] = Dictator.ip_input() ;

		DatagramSocket socks = null;
		DatagramPacket packs = null;
		InetAddress client_address = null ;

		try
		{
			client_address = InetAddress.getByAddress (ip_byte) ;
			String command_string = new String ("--COPY-- " + file_name) ;
			byte data_to_copy[] = command_string.getBytes() ;

			socks = new DatagramSocket (SERVER_PORT) ;
			packs = new DatagramPacket (data_to_copy, data_to_copy.length, client_address, CLIENT_PORT) ;

			System.out.println ("\n\nSending File Name... ") ;
			socks.setSoTimeout (5000) ;
			socks.send(packs) ;
			socks.receive(packs) ;
		}
		catch (SocketTimeoutException se)
		{
			System.out.println ("The client did not respond within 5 seconds, terminating job \n") ;
			socks.close () ;
			return ;
		}
		catch (IOException he)
		{
			System.out.println ("Something went wrong while setting up the network code : " + he) ;
			socks.close () ;
			return ;
		}

		if (new String(packs.getData()).startsWith("ACK") == true )
		{
			System.out.println ("ACK received from client at " + client_address.toString()) ;
			System.out.println ("Client message : " + new String  (packs.getData())) ;
			packs.setData (new String ("ACK").getBytes()) ;
			try
			{
				socks.send (packs) ;
			}
			catch (IOException ee)
			{
				System.out.println ("This is unexpected");
				socks.close();
				return;
			}

		}

		ServerSocket servsock = new ServerSocket(13267);
    	System.out.println("Waiting for client connection...");

        Socket sock = servsock.accept();
        System.out.println("Accepted connection : " + sock);

		File myFile = new File (file_name);
        byte [] mybytearray  = new byte [(int)myFile.length()];
        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(mybytearray,0,mybytearray.length);
        OutputStream os = sock.getOutputStream();
        System.out.println("Sending...");
        os.write(mybytearray,0,mybytearray.length);
        os.flush();
        sock.close();
	}
}

class Dictator extends Thread
{
	public static final byte SERVER_ACTIVE = 1 ;
	public static final byte SERVER_DISABLED = 0 ;

	private static final byte MENU_DO_NOTHING = 99 ;
	private static final byte MENU_EXIT = 0 ;
	private static final byte MENU_ACTIVATE_SERVER = 1 ;
	private static final byte MENU_DEACTIVATE_SERVER = 2 ;
	private static final byte MENU_MULTI = 3 ;
	private static final byte MENU_UNI = 4 ;
	private static final byte MENU_FILE_TRANSFER = 5 ;
	Scanner menu_input = new Scanner (System.in).useDelimiter("\\D+") ;


	byte menu_option = MENU_DO_NOTHING ;
	byte server_activity = SERVER_DISABLED ;
	byte something ;

	public Dictator ()
	{



	}

	public static byte[] ip_input ()
	{
		Scanner ip_input = new Scanner (System.in).useDelimiter("\\D+") ;
		Integer a ;
		byte iptargetpc[] = new byte[4] ;
		boolean must_restart = false ;
		short i ;

		do
		{
			for (i = 0 ; i < 4 ; i++)
			{
				a = ip_input.nextInt () ;
				if (a < 0 || a > 255)
				{
					System.out.print ("\nInvalid IP value : " + a + "\nPlease re-type address : \n") ;
					ip_input.useDelimiter ("\n") ;
					ip_input.next () ;		/// This command clears out all previous input by reading them
					ip_input.useDelimiter ("[^0-9]+") ;

					must_restart = true ;
					break ;
				}
				else
					iptargetpc[i] = a.byteValue() ;

			System.out.print ("\nbytevalue = " + iptargetpc[i] ) ;

				if (i == 3 && must_restart == true)
					must_restart = false ;
			}
		} while (must_restart) ;


		return iptargetpc ;
	}


	public void unicast_primaria () throws IOException, InterruptedException
	{
		final int UNIPORT_USED = 4446 ;

		byte unicast_target[] ;		/// Stores ip_address in byte form
		byte buffer[] ;		/// Stores user_message for sending
		BufferedReader message_input = new BufferedReader(new InputStreamReader(System.in));	/// A reader for user string
		String user_message ;		/// Stores user message
		InetAddress client_ip ;		/// IP address of client
		DatagramSocket socket ;
		DatagramPacket packet ;

		System.out.println ("\nUnder this option, you have to input a target IP address and a message") ;


		System.out.print ("\n\nPlease state target IP address. \n") ;
		unicast_target = ip_input() ;

		client_ip = InetAddress.getByAddress (unicast_target) ;

		System.out.println ("\n\nPlease type in your message to the client at " + client_ip.getHostAddress ()) ;
		user_message = message_input.readLine () ;
		buffer = user_message.getBytes () ;

		socket = new DatagramSocket (6000) ;		/// This should be different compared to the packet's dest port
													/// Otherwise it simply fails
		packet = new DatagramPacket (buffer, buffer.length, client_ip, UNIPORT_USED) ;
		socket.send (packet) ;

		System.out.println ("as : " + socket.getPort()) ;
		System.out.println ("Packet successfully sent : " + user_message) ;
		socket.close () ;


	}

	public void run ()
	{
		//byte user_input = MENU_DO_NOTHING ;

		System.out.println ("You are now in the server main_menu. Please specify your wants.") ;

		while (menu_option != MENU_EXIT)
		{
			if (server_activity == SERVER_DISABLED)
				System.out.println ("The server is currently not listening to anything") ;
			else if (server_activity == SERVER_ACTIVE)
				System.out.println ("The server is currently actively listening") ;

			System.out.println ("\n1. Activate Server Listener on port 4445       2. Deactivate Server Listener") ;
			System.out.println ("3. Multicast a message on port 54100           4. Unicast a message") ;
			System.out.println ("5. Transfer a file through unicast             0. Exit Program") ;
			System.out.println ("What's your job?") ;
			menu_option = menu_input.nextByte() ;
			System.out.println ("you've selected " + menu_option) ;
			switch (menu_option)
			{
				case MENU_ACTIVATE_SERVER :
					if (server_activity == SERVER_DISABLED)
			//			server_th.start() ;
						System.out.println ("damn you") ;
					else if (server_activity == SERVER_ACTIVE)
						System.out.println ("The server is already listening") ;

					break ;

				case MENU_DEACTIVATE_SERVER :
					/// do nothing
					break ;

				case MENU_MULTI :
					/// For multicasting
					try
					{
						new Propaganda() ;
					}
					catch (IOException k)
					{
						System.out.println ("Back in Menu, exception is : " + k) ;
					}
					break ;
				case MENU_UNI :
					try	/// Unicasting
					{
						unicast_primaria () ;
					}
					catch (IOException g)
					{
						System.out.println ("Back in Menu, exception is : " + g) ;
					}
					catch (InterruptedException ge)
					{
						System.out.println ("The work was interrupted : THIS IS A TEST INTERRUPT CATCH") ;
					}
					break;
				case MENU_FILE_TRANSFER :
					try
					{
						new File_Transfer () ; ;
					}
					catch (IOException l)
					{
						System.out.println ("Back in Menu, exception is : " + l) ;
					}
					break ;
				case MENU_EXIT :
					System.out.println ("\nMenu thread shutting down") ;
					break ;
				default :
					/// do nothing
					menu_option = MENU_DO_NOTHING ;
					break ;

			}
		}
	}
}

c

hope the explanation helps.....

Your description starts with: Server sends file
Where does it send it? What connections does it have to send a file to? Did you leave off some evevnts?

Does the protocol for sending a file include a header with the filename and the size of the file?

You have hardcoded too many numbers for ports etc in too many different places in the code. That will make it hard to change. There should be only one definition for these and all the code should use the same values obtained from the single definition.

server sends the file to client... it first rrequests the ip add of the client. tcp connection is used. yes, it include the file name and size of file.

server port = 8070
client port = 4446
server socket for tcp = 13267

What happens when the client tries to have an application open the received file?

nothing much. It displays but then the client is not listening anymore at the time. So, i want my code to be able to listen to the server while the displaying is being done. and i want the code to be able to run a loop where i can call one file to be displayed after another. Same as a feature of an electronic announcement board.

Does "nothing much" means that the application opens the file as you want it to?

What are the problems with the looping in the client?

I'm done for today, see you tomorrow.

i somehow don't know where to place the loop.. once it receives the file from server, it technically moves in into the queue in order for the app to open it. a basic display execution. prob is i don know how to put the file names into queues or array so that i can execute it using the runtime(). and i don know how to loop the client to keep listening at the port.

how to put the file names into queues or array

The arraylist class has an add() method.

ok...=) any idea on how to play them in an endless loop?
plus, how to keep the client listening while another thread is used to open and play the files?.. *sorry but had never done threading before*

What do you mean by "play" them?
begin loop
get next file, wrap around to first when past end
play file
end loop

sorry, i mean executing the file...

do u have the code for threading in java? am not sure how to implement them.. just codes to show two different tasks is executed by 2 threads...

hmmm... will do..=) thanks for ur help... will keep posting if i find any gliches...=)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.