The Artima Developer Community
Sponsored Link

Java Answers Forum
I (Java beginner) NEED HELP with Server & Client Code!!!!

1 reply on 1 page. Most recent reply: Jul 3, 2002 10:41 PM by Pavan Kumar Keely

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
moh r jee

Posts: 3
Nickname: mohrjee
Registered: Jun, 2002

I (Java beginner) NEED HELP with Server & Client Code!!!! Posted: Jul 3, 2002 8:42 AM
Reply to this message Reply
Advertisement
Hi there!
Could someone tell me what's wrong with my code, please? Could you also tell me what I did wrong and explain it to me?
I suspect problems with the I/O streams, but I'm not sure.
All help would be appreciated!
My email address is:
msebesty@bigpond.net.au[/i]
[u]Code Object
[/u] The Server is supposed to load and send the array object over to the Client, where the Client receives it, processes it and sends the array back to the Server where it saves it to fil][u]N[/b][/u] All this is done over ONE computer in two separate (DOS / JE Creator) windows.
It won't go over a network, not even to a neighboring.

[
ie
[java]import java.io.*;
import java.net.*;
 
public class AddressDataClient implements Serializable
{
		
	public static void main (String[] args)
	{
		
		int arraySize = 4;
		AddressData[] aDetails = new AddressData[arraySize]; //input into memory (RAM): instance of array (size3)
	
		for(int i = 0;i<aDetails.length;i++) //inputs default data into declared array 
			aDetails[i] = new AddressData();
		
		aDetails = ReadData(aDetails);
	
		int choices =0;
			//shows menu until quit condition is met
		do 
		{
			choices = printMenu();//shows menu and gets input
			choices = menuSelect(choices, aDetails, arraySize);//processes input
		} while (choices != -1);
		
		WriteData(aDetails);
		SaveData(aDetails);
	}
 
	public static int printMenu()  
	{
        System.out.println("\nPlease Select from the following options:");
        System.out.println("[1] Add\n[2] Modify\n[3] Delete\n[4] Search\n[5] Display\n[6] Quit");
		int choice = MyInput.readInt();//choice declared and initialised in one step
		return choice;
	}
	//input : an integer choice holding the users menu selection
	//	: an AddressData object aDetails where address data is stored
	//output: returns an integer choice to control loop in main
	//processes menu selection and calls further functionality
	
	public static int menuSelect(int choice, AddressData[] aDetails, int arraySize) 
	{
		switch(choice) 
		{
		case 1:Add(aDetails, arraySize);
		break;
		case 2:Modify(aDetails);
		break;
		case 3:Delete(aDetails); 
		break;
		case 4:Search(aDetails); 
		break;
		case 5:Display(aDetails);
		break;
		case 6:System.out.println("Thank You for using this. Goodbye!");  
	  	choice = -1;
	  	break;
	  	default:System.out.println("Invalid Selection - try again");
		}
		return choice;
	}
	//input : an integer choice holding the users menu selection
	//	: an AddressData object aDetails where address data is stored
	//output: returns an integer choice to control loop in main
	//processes user choice and calls chosen method
 
	public static void Search(AddressData[] aDetails)
	{
		int result =0;
		String name;
 
		for(int i =0;i<aDetails.length;i++)
		{
			aDetails[i].PrintAll();
		}
		
 
		System.out.print("Enter the LAST NAME you wish to search for -> ");
		name = MyInput.readString();
		result = SearchLastName(aDetails, name);
				
		
		if(result != -1)
		{
			System.out.println("The record was found at position " +result+ "\n");
		}else{
			System.out.println("No record found with the surname " +name+ "\n");
		}
	}
	//input: an addressdata object aDetails where address data is stored
	//			integer result (from SearchLastName method)
	//output: prints AddressData aDetails to screen
	//			AddressData object aDeatails along with a string name datatype object
	//prints out AddressData aDetails to screen, searches aDetails for user's entry by pasing string
	//to "SearchLastName" method and prints result to screen.
		
		
	public static int SearchLastName(AddressData[] aDetails, String surname)
	{
		int result=-1;
			
		for(int i =0;i<aDetails.length;i++)
			if(aDetails[i].getLastName().equalsIgnoreCase(surname))
		
		result = i;
		return result;
	}
	//input: AddressData object aDetails along with a string namedatatype object
	//output: returns an integer result to its calling method
	//searches aDetails for string surname (from Search method) and returns integer result
		
 
	public static void Add(AddressData[] aDetails, int arraySize)
	{
		String firstname, lastname, street, suburb = null;
		int streetnum, code = 0;
		
		//This decrement is to obtain correct array size:
		arraySize--;	
		
		//Check whether the array is full:
		if(aDetails[arraySize].getFirstName() != "firstname")
		{
			System.out.println("ERROR: Cannot add entry because AddressBook maybe full. Please first delete an\n\tentry to add new entry or modify an existing entry.\n\t(IGNORE THIS MESSAGE IF PROMPTED TO ENTER FIRSTNAME)\n");
		}
	
		for(int i =0;i<aDetails.length;i++)
			if(aDetails[i].getFirstName() == "firstname")
			{
				System.out.print("Enter FirstName -> ");
				firstname = MyInput.readString();
				aDetails[i].setFirstName(firstname);
				System.out.print("Enter LastName -> ");
				lastname = MyInput.readString();
				aDetails[i].setLastName(lastname);
				System.out.print("Enter Street Number -> ");
				streetnum = MyInput.readInt();
				aDetails[i].setStreetNumber(streetnum);
				System.out.print("Enter StreetName -> ");
				street = MyInput.readString();
				aDetails[i].setStreetName(street);
				System.out.print("Enter Suburb -> ");
				suburb = MyInput.readString();
				aDetails[i].setSuburb(suburb);
				System.out.print("Enter PostCode -> ");
				code = MyInput.readInt();
				aDetails[i].setPostCode(code);
				i = aDetails.length;
			}
	}
	//input: AddressData object aDetails 
	//output: modified AddressData aDetails, screen output of menu, new AdressData aDetails entry 
	//'for' loop looks for an "empty" spot in AddressData aDetails, if found user enters new entry if not user is given
	//a message. 
 
	public static void Delete(AddressData[] aDetails)
	{
		int iUser, result =0;
		String name, firstname, lastname, street, suburb = null;
				
		for(int i =0;i<aDetails.length;i++)
		{
			aDetails[i].PrintAll();
		}
		
		System.out.print("Enter the LAST NAME you wish to delete -> ");
		name = MyInput.readString();
		result = SearchLastName(aDetails, name);
				
		if(result != -1)
		{
			System.out.println("The record was found at position " +result+ "\n");
		}else{
			System.out.println("No record found with the surname " +name+ "\n");
		}
		
		System.out.print("\nDo you wish to delete this entry?\n[1] Yes\n[2] No: ");
		iUser = MyInput.readInt();
			
		while(iUser < 1 || iUser >2)
		{
			System.out.print("Invalid Choice. Please enter either 1 or 2: ");
			iUser = MyInput.readInt();
		}
			
		if(iUser == 1)
		{
			aDetails[result].setFirstName("firstname");
			aDetails[result].setLastName("lastname");
			aDetails[result].setStreetNumber(0);
			aDetails[result].setStreetName("street");
			aDetails[result].setSuburb("suburb");
			aDetails[result].setPostCode(0);
		}
				
	}
	//input: AddressData object aDetails along with a string datatype object
	//output: AddressData object and String name (to SearchLastName)
	//			Screen prompts
	//method delete prints contents of AddressData aDetails to screen, searches for user's entry
	//if user chooses to delete then record is reset to default data.
	
	public static void Display(AddressData[] aDetails)
	{
		int result, iUser =0;
		String name ;
 
		System.out.print("\nChoose whether you want to:\n[1] View ALL entries\n[2] View AN entry\n");
		iUser = MyInput.readInt();
			
		while(iUser < 1 || iUser >2)//error check user input
		{
			System.out.print("Invalid Choice. Please enter either 1 or 2");
			iUser = MyInput.readInt();
		}
		
		if(iUser ==1)
		{
			for(int i =0;i<aDetails.length;i++)
			{
				aDetails[i].PrintAll();
			}
		}else{
			System.out.print("Enter the LAST NAME you wish to search for -> ");
			name = MyInput.readString();
			result = SearchLastName(aDetails, name);
				
			if(result != -1)
			{
				System.out.println("The record was found at position " +result+ "\n");
				aDetails[result].PrintAll();
			}else{
				System.out.println("No record found with the surname " +name+ "\n");
			}
		}
	}
	//input: AddressData object aDetails and integer result
	//output: AddressData object aDetails or just a record of Address aDetails to screen
	//			string name (to SearchLastName)
	//Prompts user for choice between viewing an entry or all entries. Prints either an entry
	//or the entire AddressData aDetails to screen
 
	public static void Modify(AddressData[] aDetails)
	{
		int result;
		int choices =0;
		String name;
			
		System.out.print("Enter the LAST NAME you wish to search for -> ");
		name = MyInput.readString();
		result = SearchLastName(aDetails, name);
				
		if(result != -1)
		{
			System.out.println("The record was found at position " +result+ "\n");
		}else{
			System.out.println("No record found with the surname " +name+ "\n");
		}
		
		do 
		{
			choices = printModifyMenu(aDetails, result);//shows modify menu and gets input
		} while (choices != -1);
		
	}
	//input: AddressData object aDetails and integer result, user input choice
	//output:Addressdata object aDetails,  string name and result
	//User enters string to search, string name passed to SearchLastName method, prints result of
	//SearchLastName shows modify menu and gets user input
	
	public static int printModifyMenu(AddressData[] aDetails, int result)
	{
			
		String name, firstname, lastname, street, suburb = null;
		int streetnum, code = 0;			
			
		System.out.println("\nChoose from the following options what you want to modify:"); 
		System.out.println("[1] FirstName\n[2] LastName\n[3] StreetNumber\n[4] StreetName\n[5] Suburb\n[6] PostCode\n[7] Quit this\n");
		int choice = MyInput.readInt();
	
		switch(choice) 
		{
			case 1:	System.out.print("Enter NEW FirstName -> ");
				firstname = MyInput.readString();
				aDetails[result].setFirstName(firstname);
				break;
			case 2: System.out.print("Enter NEW LastName -> ");
				lastname = MyInput.readString();
				aDetails[result].setLastName(lastname);
				break;
			case 3:	System.out.print("Enter NEW Street Number -> ");
				streetnum = MyInput.readInt();
				aDetails[result].setStreetNumber(streetnum);
				break;
			case 4: System.out.print("Enter NEW StreetName -> ");
				street = MyInput.readString();
				aDetails[result].setStreetName(street);
				break;
			case 5:	System.out.print("Enter NEW Suburb -> ");
				suburb = MyInput.readString();
				aDetails[result].setSuburb(suburb);
				break;
			case 6: System.out.print("Enter NEW PostCode -> ");
				code = MyInput.readInt();
				aDetails[result].setPostCode(code);
				break;
			case 7:	choice = -1;
	  			break;
	  		default:System.out.println("Invalid Selection - try again");
		}
		
		return choice;
	}
	//input: AddressData object aDetails and gets user input choice
	//outputs: prints menu to screen, AddressData adetails data, and integer choice
	//Modify menu is continously printed, awaits user input and user modificaion of specific aDetails data
	//returns integer choice.
	
	public static AddressData[] ReadData(AddressData[] aDetails)
	{
		try
		{
			System.out.println("CLIENT STARTED...\n");
				
			//Create instance of socket
			Socket connectToServer = new Socket("localhost", 8000);
			
			//Setup input and output stream from/to server
			
			ObjectOutputStream oos = new ObjectOutputStream(connectToServer.getOutputStream());
			ObjectInputStream ois = new ObjectInputStream(connectToServer.getInputStream());
			
			System.out.println("Waiting for object from server...");
			aDetails =(AddressData[])ois.readObject();
			System.out.println("Object received from server!");
			
		}
		
		catch(Exception ex)
		{
			System.err.println(ex);
		}
		
		return aDetails;
	}
	
	public static void WriteData(AddressData[] aDetails)
	{
		try
		{
			//Create instance of socket
			Socket connectToServer = new Socket("localhost", 8000);
			System.out.println("Connection Accepted!");
			
			//Setup input and output stream from/to server
			//ObjectInputStream ois = new ObjectInputStream(connectToServer.getInputStream());
			ObjectOutputStream oos = new ObjectOutputStream(connectToServer.getOutputStream());
			System.out.println("Streams created!");
			
			System.out.println("Sending object to server...");
			oos.writeObject(aDetails);
			System.out.println("Object sent to server...");
		}
		
		catch(Exception ex)
		{
			System.err.println(ex);
		}
	}
	//input: AddressData object aDetails
	
	public static void SaveData(AddressData[] aDetails)
	{
		File fAddress = new File("addresses.adr");
		try
		{
			ObjectOutputStream OosAddress = new ObjectOutputStream(new FileOutputStream(fAddress));
			for(int i = 0;i<aDetails.length;i++)
			{
				if((aDetails[i].getFirstName() != "firstname")&&(aDetails[i].getLastName() != "lastname"))
				{
					OosAddress.writeObject(aDetails[i]);
				}
			}
		
			OosAddress.close();
		}
		
		catch(IOException ex)
		{
			System.out.println(ex.getMessage());
		}
	}
}
//end of AddressDataCli
a[va]
[b
ve
[java]import java.io.*;
import java.net.*;
 
public class AddressDataServer implements Serializable
{
	public static void main (String[] args)
	{
		int arraySize = 4;
		AddressData[] aDetails = new AddressData[arraySize]; 
				
		for(int i = 0;i<aDetails.length;i++) //inputs default data into declared array 
			aDetails[i] = new AddressData();
 
		LoadData(aDetails); //inputs saved data from "addresses.adr"
		
		System.out.println("***RECORDS LOADED***\n");
		
		for(int i = 0;i<aDetails.length;i++)
		aDetails[i].PrintAll();
		
		try
		{
			System.out.println("SERVER STARTED...\n");
						
			//Create Server Socket
			ServerSocket servSock = new ServerSocket(8000);
			
			//Listen on serversocket for connection attempts and continue when a client actually does connect
			System.out.println("Waiting for Client to Connect...");
			Socket connectToClient = servSock.accept();
			System.out.println("Connection Accepted!");
			
			//Create input and output streams for data from/to client
			System.out.println("Creating Input and Output Streams...");
			ObjectInputStream ois = new ObjectInputStream(connectToClient.getInputStream());
			ObjectOutputStream oos = new ObjectOutputStream(connectToClient.getOutputStream());
			System.out.println("Streams created!");
			
			//Loop forever (at least until there is no IP connection, at which point an exception will be thrown)
			while(true)
			{
				System.out.println("Waiting...");
				
				//Send array to client
				System.out.println("Sending object to client...");
				oos.writeObject(aDetails);
				System.out.println("Object sent to client!");
		
				//Receive array from client
				System.out.println("Waiting for object from client...");
				aDetails =(AddressData[])ois.readObject();
				System.out.println("Object received from client!");
				
				//Save (modified) array (to addresses.adr):
				SaveData(aDetails);	
			}
		}
		
		catch(Exception ex)
		{
			System.err.println(ex);
		}
	}
	
	public static void LoadData(AddressData[] aDetails)
	{
		File fAddress = new File("addresses.adr");
		
		try
		{
			ObjectInputStream OisAddress = new ObjectInputStream(new FileInputStream(fAddress));
			for(int i = 0;i<aDetails.length;i++)
			{
				aDetails[i] = (AddressData)OisAddress.readObject();
			}
			OisAddress.close();
		}
		
		catch(EOFException endOfFileException)
		{
			System.out.println("All records loaded.\n");
		}
		
		catch(ClassNotFoundException classNotFoundException)
		{
			System.out.println("File does not contain data excepted\n");
		}
		
		catch(IOException ex)
		{
			System.out.println(ex.getMessage());
		}
	}
	//input: AddressData object aDetails, EOFException endOfFileexception, ClassNotFoundException 
	//classNotFoundException and IOException ex 
	//output: OisAddress.readObject().
	
	public static void SaveData(AddressData[] aDetails)
	{
		File fAddress = new File("addresses.adr");
		try
		{
			ObjectOutputStream OosAddress = new ObjectOutputStream(new FileOutputStream(fAddress));
			for(int i = 0;i<aDetails.length;i++)
			{
				if((aDetails[i].getFirstName() != "firstname")&&(aDetails[i].getLastName() != "lastname"))
				{
					OosAddress.writeObject(aDetails[i]);
				}
			}
		
			OosAddress.close();
		}
		
		catch(IOException ex)
		{
			System.out.println(ex.getMessage());
		}
	}
	//input: AddressData object aDetails, EOFException endOfFileexception, ClassNotFoundException 
	//classNotFoundException and IOException ex 
	//output: OisAddress.readObject().	
}
//end of AddressDataSer
a[/java]


Pavan Kumar Keely

Posts: 7
Nickname: pavan
Registered: Mar, 2002

Re: I (Java beginner) NEED HELP with Server & Client Code!!!! Posted: Jul 3, 2002 10:41 PM
Reply to this message Reply
hi,

Just tell me what's your exact problem ??? Are you getting any exception or an error ??? If you tell the probelm then I'll try to solve your problem...

the type of problems you may get are:
1. Probelm with the Object Streams. When the ObjectInputStream is constructed then it expects the magic header from the recipient. If it doesn't get that number, then it throws an exception.

2. Any socket level problems.

please specify the problem...
bye
Pavan Kumar Keely,
Software Engineer, Quillis India

Flat View: This topic has 1 reply on 1 page
Topic: download file from webobjects and report... Previous Topic   Next Topic Topic: can I call a c++ function ?

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use