--- /dev/null
+public class BankAccount\r
+{\r
+ //can't init here, won't compile, do it in the constructor\r
+ \r
+ //nine digits\r
+ String AccountNumber; //field #1\r
+ \r
+ //account owner's name\r
+ //always 10 chars\r
+ //pad with @\r
+ String FirstName; //field #2 \r
+ String MiddleName; //field #3\r
+ String LastName; //field #4\r
+ \r
+ //1 == Savings\r
+ //2 == Checking\r
+ //3 == Teller\r
+ String AccountType; //field #5\r
+ \r
+ //ints only, should use floats in the future\r
+ //1234567890\r
+ //assumes balance does is never negative\r
+ //always 10 chars\r
+ //pad with @\r
+ String Balance; //field #6\r
+ \r
+ //four digits\r
+ String PIN; //field #7\r
+ \r
+ public BankAccount()\r
+ {\r
+ \r
+ }\r
+ \r
+ public BankAccount(String account, String first, String middle, String last, String type, String balance, String pin)\r
+ {\r
+ if(account != null)\r
+ AccountNumber = account;\r
+ if(first != null) \r
+ FirstName = first;\r
+ if(middle != null)\r
+ MiddleName = middle;\r
+ if(last != null)\r
+ LastName = last;\r
+ if(type != null)\r
+ AccountType = type;\r
+ if(balance != null)\r
+ Balance = balance;\r
+ if(pin != null)\r
+ PIN = pin;\r
+ }\r
+ \r
+ public void modifyAccount(String account, String first, String middle, String last, String type, String balance, String pin)\r
+ {\r
+ if(account != null)\r
+ AccountNumber = account;\r
+ if(first != null) \r
+ FirstName = first;\r
+ if(middle != null)\r
+ MiddleName = middle;\r
+ if(last != null)\r
+ LastName = last;\r
+ if(type != null)\r
+ AccountType = type;\r
+ if(balance != null)\r
+ Balance = balance;\r
+ if(pin != null)\r
+ PIN = pin;\r
+ }\r
+}\r
--- /dev/null
+//Banking Application Server\r
+\r
+/* Startup object is generated with the initialstate flag set by the\r
+ * system to start the computation up */\r
+\r
+task Startup(StartupObject s{initialstate})\r
+{\r
+ System.printString("Starting\n");\r
+ ServerSocket ss = new ServerSocket(8080);\r
+ System.printString("Creating ServerSocket\n");\r
+ BankDatabase Bank = new BankDatabase(){DatabaseInit};\r
+ taskexit(s{!initialstate}); /* Turns initial state flag off, so this task won't refire */\r
+}\r
+\r
+task AcceptConnection(ServerSocket ss{SocketPending})\r
+{\r
+ BankAppSocket bas = new BankAppSocket(){BASocketInit};\r
+ ss.accept(bas);\r
+ System.printString("Connected\n");\r
+}\r
+\r
+//i think this task could probably be broken up into smaller tasks\r
+task ProcessRequest(BankAppSocket bas{IOPending && BASocketInit}, BankDatabase Bank{DatabaseInit})\r
+{\r
+ String message = new String(bas.receive());\r
+ //System.printString(message);\r
+ \r
+ //login\r
+ if(message.startsWith("1"))\r
+ {\r
+ String account = message.subString(1, 10);\r
+ String pin = message.subString(10, 14);\r
+ \r
+ for(int i = 0; i < Bank.numOfAccounts; i++)\r
+ {\r
+ if(Bank.database[i].AccountNumber.equals(account) && Bank.database[i].PIN.equals(pin))\r
+ {\r
+ bas.send("Login OK");\r
+ //System.printString("Login OK");\r
+ }\r
+ else\r
+ {\r
+ bas.send("Login Error");\r
+ //System.printString("Login Error");\r
+ }\r
+ }\r
+ }\r
+ //logout\r
+ else if(message.startsWith("2"))\r
+ {\r
+ String account = message.subString(1, 10);\r
+ \r
+ //find the account\r
+ for(int i = 0; i < Bank.numOfAccounts; i++)\r
+ {\r
+ if(Bank.database[i].AccountNumber.equals(account))\r
+ {\r
+ bas.send("Logout OK");\r
+ //System.printString("Logout OK");\r
+ }\r
+ else\r
+ {\r
+ bas.send("Logout Error");\r
+ //System.printString("Logout Error");\r
+ }\r
+ }\r
+ }\r
+ //create\r
+ else if(message.startsWith("3"))\r
+ {\r
+ String account = message.subString(1, 10);\r
+ String first = message.subString(10, 20);\r
+ String middle = message.subString(20, 30);\r
+ String last = message.subString(30, 40);\r
+ String type = message.subString(40, 41);\r
+ String balance = message.subString(41, 51);\r
+ String pin = message.subString(51, 55);\r
+ \r
+ //find first empty space\r
+ int id = -1;\r
+ for(int i = 0; i < Bank.numOfAccounts; i++)\r
+ {\r
+ if(Bank.database[i].AccountNumber.equals("@@@@@@@@@"))\r
+ id = i;\r
+ }\r
+ \r
+ if(id != -1)\r
+ {\r
+ //should check for input errors first but...\r
+ Bank.database[id].AccountNumber = first;\r
+ Bank.database[id].FirstName = middle;\r
+ Bank.database[id].MiddleName = last;\r
+ Bank.database[id].LastName = last;\r
+ Bank.database[id].AccountType = type;\r
+ Bank.database[id].Balance = balance;\r
+ Bank.database[id].PIN = pin;\r
+ \r
+ Bank.numOfAccounts++;\r
+ \r
+ bas.send(Bank.database[id].AccountNumber);\r
+ //System.printString(Bank.database[id].AccountNumber);\r
+ }\r
+ else\r
+ {\r
+ bas.send("Create Error");\r
+ //System.printString("Create Error");\r
+ }\r
+ }\r
+ //delete\r
+ else if(message.startsWith("4"))\r
+ {\r
+ String account = message.subString(1, 10);\r
+ \r
+ //find the account\r
+ int id = -1;\r
+ for(int i = 0; i < Bank.numOfAccounts; i++)\r
+ {\r
+ if(Bank.database[i].AccountNumber.equals(account))\r
+ id = i;\r
+ }\r
+ \r
+ if(id != -1)\r
+ {\r
+ Bank.database[id].AccountNumber = "@@@@@@@@@@";\r
+ Bank.database[id].FirstName = "@@@@@@@@@@";\r
+ Bank.database[id].MiddleName = "@@@@@@@@@@";\r
+ Bank.database[id].LastName = "@@@@@@@@@@";\r
+ Bank.database[id].AccountType = "@";\r
+ Bank.database[id].Balance = "@@@@@@@@@@";\r
+ Bank.database[id].PIN = "@@@@";\r
+ Bank.numOfAccounts--;\r
+ \r
+ bas.send("Close Account OK");\r
+ //System.printString("Close Account OK");\r
+ }\r
+ else\r
+ {\r
+ bas.send("Close Account Error");\r
+ //System.printString("Close Account Error");\r
+ }\r
+ }\r
+ //modify\r
+ else if(message.startsWith("5"))\r
+ {\r
+ String account = message.subString(1, 10);\r
+ String field = message.subString(10, 11);\r
+ //two digits 00-99\r
+ String numBytes = message.subString(11, 13);\r
+ String data = message.subString(13, 13 + Integer.parseInt(numBytes));\r
+ \r
+ //find the account\r
+ int id = -1;\r
+ for(int i = 0; i < Bank.numOfAccounts; i++)\r
+ {\r
+ if(Bank.database[i].AccountNumber.equals(account))\r
+ id = i;\r
+ }\r
+ \r
+ if(id != -1)\r
+ {\r
+ //maybe shouldn't allow changes to some of these fields\r
+ if(field.equals("1"))\r
+ {\r
+ Bank.database[id].AccountNumber = data;\r
+ }\r
+ else if(field.equals("2"))\r
+ {\r
+ Bank.database[id].FirstName = data;\r
+ }\r
+ else if(field.equals("3"))\r
+ {\r
+ Bank.database[id].MiddleName = data;\r
+ }\r
+ else if(field.equals("4"))\r
+ {\r
+ Bank.database[id].LastName = data;\r
+ }\r
+ else if(field.equals("5"))\r
+ {\r
+ Bank.database[id].AccountType = data;\r
+ }\r
+ else if(field.equals("6"))\r
+ {\r
+ Bank.database[id].Balance = data;\r
+ }\r
+ else if(field.equals("7"))\r
+ {\r
+ Bank.database[id].PIN = data;\r
+ }\r
+ \r
+ bas.send("Modify OK");\r
+ //System.printString("Modify OK");\r
+ }\r
+ else\r
+ {\r
+ bas.send("Modify Error");\r
+ //System.printString("Modify Error");\r
+ }\r
+ }\r
+ //check account info\r
+ else if(message.startsWith("6"))\r
+ {\r
+ String account = message.subString(1, 10);\r
+ \r
+ //find the account\r
+ int id = -1;\r
+ for(int i = 0; i < Bank.numOfAccounts; i++)\r
+ {\r
+ if(Bank.database[i].AccountNumber.equals(account))\r
+ id = i;\r
+ }\r
+ \r
+ if(id != -1)\r
+ {\r
+ StringBuffer strBuffer = new StringBuffer(Bank.database[id].AccountNumber);\r
+ strBuffer.append(Bank.database[id].FirstName);\r
+ strBuffer.append(Bank.database[id].MiddleName);\r
+ strBuffer.append(Bank.database[id].LastName);\r
+ strBuffer.append(Bank.database[id].AccountType);\r
+ strBuffer.append(Bank.database[id].Balance);\r
+ strBuffer.append(Bank.database[id].PIN);\r
+ \r
+ bas.send(strBuffer.toString());\r
+ //System.printString(strBuffer.toString());\r
+ }\r
+ else\r
+ {\r
+ bas.send("Check Account Info Error");\r
+ //System.printString("Check Account Info Error");\r
+ }\r
+ \r
+ }\r
+ //deposit\r
+ //more string operations or a Float Object could be useful here \r
+ else if(message.startsWith("7"))\r
+ {\r
+ String account = message.subString(1, 10);\r
+ //two digits 00-99\r
+ //dollar part only\r
+ String numBytes = message.subString(10, 12);\r
+ //get dollars\r
+ String data = message.subString(12, 12 + Integer.parseInt(numBytes));\r
+ \r
+ \r
+ //find the account\r
+ int id = -1;\r
+ for(int i = 0; i < Bank.numOfAccounts; i++)\r
+ {\r
+ if(Bank.database[i].AccountNumber.equals(account))\r
+ id = i;\r
+ }\r
+ \r
+ if(id != -1)\r
+ { \r
+ Integer sum = new Integer(Integer.parseInt(Bank.database[id].Balance) + Integer.parseInt(data));\r
+ \r
+ StringBuffer sumBuffer = new StringBuffer(sum.toString());\r
+ \r
+ int padding = 10 - sumBuffer.length();\r
+ \r
+ for(int i = 0; i < padding; i++)\r
+ {\r
+ sumBuffer.append("@");\r
+ }\r
+ \r
+ //assumes no overflow\r
+ Bank.database[id].Balance = sumBuffer.toString();\r
+ \r
+ bas.send("Deposit OK");\r
+ //System.printString("Deposit OK");\r
+ }\r
+ else\r
+ {\r
+ bas.send("Deposit Error");\r
+ //System.printString("Deposit Error");\r
+ }\r
+ }\r
+ //withdraw\r
+ else if(message.startsWith("8"))\r
+ {\r
+ String account = message.subString(1, 10);\r
+ //two digits 00-99\r
+ //dollar part only\r
+ String numBytes = message.subString(10, 12);\r
+ //get dollars\r
+ String data = message.subString(12, 12 + Integer.parseInt(numBytes));\r
+ \r
+ //find the account\r
+ int id = -1;\r
+ for(int i = 0; i < Bank.numOfAccounts; i++)\r
+ {\r
+ if(Bank.database[i].AccountNumber.equals(account))\r
+ id = i;\r
+ }\r
+ \r
+ if(id != -1)\r
+ {\r
+ Integer difference = new Integer(Integer.parseInt(Bank.database[id].Balance) - Integer.parseInt(data));\r
+ \r
+ if(difference.intValue() >= 0)\r
+ {\r
+ StringBuffer difBuffer = new StringBuffer(difference.toString());\r
+ \r
+ int padding = 10 - difBuffer.length();\r
+ \r
+ for(int i = 0; i < padding; i++)\r
+ {\r
+ difBuffer.append("@");\r
+ }\r
+ \r
+ //assumes no overflow\r
+ Bank.database[id].Balance = difBuffer.toString();\r
+ \r
+ bas.send("Withdraw OK");\r
+ //System.printString("Withdraw OK");\r
+ }\r
+ else\r
+ {\r
+ bas.send("Overdraw Error");\r
+ //System.printString("Overdraw Error");\r
+ }\r
+ }\r
+ else\r
+ {\r
+ bas.send("Withdraw Error");\r
+ //System.printString("Withdraw Error");\r
+ }\r
+ }\r
+ //check balance\r
+ else if(message.startsWith("9"))\r
+ {\r
+ String account = message.subString(1, 10);\r
+ \r
+ int id = -1;\r
+ for(int i = 0; i < Bank.numOfAccounts; i++)\r
+ {\r
+ if(Bank.database[i].AccountNumber.equals(account))\r
+ id = i;\r
+ }\r
+ \r
+ if(id != -1)\r
+ {\r
+ bas.send(Bank.database[id].Balance);\r
+ //System.printString(Bank.database[id].Balance);\r
+ }\r
+ else\r
+ {\r
+ bas.send("Check Balance Error");\r
+ //System.printString("Check Balance Error");\r
+ }\r
+ }\r
+ else\r
+ {\r
+ bas.send("Message Error");\r
+ //System.printString("Message Error");\r
+ }\r
+}\r
--- /dev/null
+101010101Tony@@@@@@Stone@@@@@Smith@@@@@2123456@@@@8888
\ No newline at end of file
--- /dev/null
+public class BankAppSocket extends Socket\r
+{\r
+ flag BASocketInit;\r
+ \r
+ public BankAppSocket()\r
+ {\r
+ \r
+ }\r
+ \r
+ public void send(String message)\r
+ {\r
+ write(message.getBytes());\r
+ }\r
+ \r
+ public String receive()\r
+ {\r
+ byte buffer[] = new byte[64];\r
+ \r
+ int numbytes = read(buffer);\r
+ \r
+ //it's subString() not substring() like in Java\r
+ String message = (new String(buffer)).subString(0, numbytes);\r
+ \r
+ return message;\r
+ }\r
+}\r
--- /dev/null
+101010101Tony@@@@@@Stone@@@@@Smith@@@@@2123456@@@@8888
\ No newline at end of file
--- /dev/null
+public class BankDatabase\r
+{\r
+ flag DatabaseInit;\r
+\r
+ BankAccount[] database;\r
+ int numOfAccounts;\r
+ \r
+ public BankDatabase()\r
+ {\r
+ //6 pre-created accounts\r
+ numOfAccounts = 6;\r
+ \r
+ //10 account limit\r
+ database = new BankAccount[10];\r
+ \r
+ for(int i = 0; i < 10; i++)\r
+ {\r
+ database[i] = new BankAccount();\r
+ }\r
+ \r
+ //some hardcoded values\r
+ database[0].modifyAccount("123456789", "John@@@@@@", "Q@@@@@@@@@", "Public@@@@", "1", "256000001@", "2007");\r
+ database[1].modifyAccount("987654321", "Nancy@@@@@", "H@@@@@@@@@", "Private@@@", "2", "166@@@@@@@", "1234");\r
+ database[2].modifyAccount("000111000", "Paul@@@@@@", "Wellington", "Franks@@@@", "1", "454225@@@@", "0000");\r
+ database[3].modifyAccount("211411911", "Felix@@@@@", "the@@@@@@@", "Cat@@@@@@@", "3", "0@@@@@@@@@", "9999");\r
+ database[4].modifyAccount("111000111", "Paul@@@@@@", "Wellington", "Franks@@@@", "2", "1128989@@@", "0000");\r
+ //empty\r
+ database[5].modifyAccount("@@@@@@@@@", "@@@@@@@@@@", "@@@@@@@@@@", "@@@@@@@@@@", "@", "@@@@@@@@@@", "@@@@");\r
+ database[6].modifyAccount("@@@@@@@@@", "@@@@@@@@@@", "@@@@@@@@@@", "@@@@@@@@@@", "@", "@@@@@@@@@@", "@@@@");\r
+ database[7].modifyAccount("@@@@@@@@@", "@@@@@@@@@@", "@@@@@@@@@@", "@@@@@@@@@@", "@", "@@@@@@@@@@", "@@@@");\r
+ database[8].modifyAccount("@@@@@@@@@", "@@@@@@@@@@", "@@@@@@@@@@", "@@@@@@@@@@", "@", "@@@@@@@@@@", "@@@@");\r
+ database[9].modifyAccount("@@@@@@@@@", "@@@@@@@@@@", "@@@@@@@@@@", "@@@@@@@@@@", "@", "@@@@@@@@@@", "@@@@");\r
+ \r
+ //test read into database[5]\r
+ ReadFile(5);\r
+ \r
+ //test write from database[5]\r
+ WriteFile(database[5].AccountNumber, database[5].FirstName, database[5].MiddleName, database[5].LastName, database[5].AccountType, database[5].Balance, database[5].PIN);\r
+ }\r
+ \r
+ /* what, no destructor?\r
+ public ~BankDatabase()\r
+ {\r
+ //test write from database[5] \r
+ }*/\r
+ \r
+ public void ReadFile(int index) \r
+ {\r
+ //need to check if read/write works the way I think it does\r
+ String filename="BankAppRead.dat";\r
+ FileInputStream fis = new FileInputStream(filename);\r
+ \r
+ byte account[] = new byte[9];\r
+ byte first[] = new byte[10];\r
+ byte middle[] = new byte[10];\r
+ byte last[] = new byte[10];\r
+ byte type[] = new byte[1];\r
+ byte balance[] = new byte[10];\r
+ byte pin[] = new byte[4];\r
+ \r
+ //read one account for now\r
+ fis.read(account);\r
+ fis.read(first);\r
+ fis.read(middle);\r
+ fis.read(last);\r
+ fis.read(type);\r
+ fis.read(balance);\r
+ fis.read(pin);\r
+ \r
+ fis.close();\r
+ \r
+ String S1 = new String(account);\r
+ //System.printString(S1);\r
+ String S2 = new String(first);\r
+ //System.printString(S2);\r
+ String S3 = new String(middle);\r
+ //System.printString(S3);\r
+ String S4 = new String(last);\r
+ //System.printString(S4);\r
+ String S5 = new String(type);\r
+ //System.printString(S5);\r
+ String S6 = new String(balance);\r
+ //System.printString(S6);\r
+ String S7 = new String(pin);\r
+ //System.printString(S7);\r
+ \r
+ //read into one account for now\r
+ database[index].modifyAccount(S1, S2, S3, S4, S5, S6, S7);\r
+ }\r
+ \r
+ public void WriteFile(String account, String first, String middle, String last, String type, String balance, String pin) \r
+ {\r
+ String filename="BankAppWrite.dat";\r
+ FileOutputStream fos = new FileOutputStream(filename);\r
+ \r
+ //write one account for now\r
+ fos.write(account.getBytes());\r
+ fos.write(first.getBytes());\r
+ fos.write(middle.getBytes());\r
+ fos.write(last.getBytes());\r
+ fos.write(type.getBytes());\r
+ fos.write(balance.getBytes());\r
+ fos.write(pin.getBytes());\r
+ \r
+ fos.close();\r
+ }\r
+}\r
--- /dev/null
+// Bank App in Java
+
+// Author: Danish Lakhani
+
+// BankAppServer - Bank Application Server that services one client at a time
+
+import java.io.*;
+import java.net.*;
+import java.util.*;
+
+class BankAppClientTeller
+{
+ static int SUCCESS = 0;
+ static int ERROR = 1;
+
+ static int LOGIN_ACCOUNT = 1;
+ static int LOGIN_PIN = 2;
+
+ static int ACCOUNT_SAVINGS = 1;
+ static int ACCOUNT_CHECKING = 2;
+ static int ACCOUNT_TELLER = 3;
+
+ private Socket mySocket = null;
+ private PrintWriter out = null;
+ private BufferedReader in = null;
+ private static int serverPort = 44444;
+
+ public BankAppClientTeller()
+ {
+ }
+
+ private void establishConnection()
+ throws IOException
+ {
+ System.out.println("Connecting to server...");
+ mySocket = new Socket("localhost", serverPort);
+ out = new PrintWriter(mySocket.getOutputStream(), true);
+ in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
+ System.out.println("Connection Established!");
+ }
+
+ private void closeConnection()
+ throws IOException
+ {
+ if (out != null)
+ out.close();
+ if (in != null)
+ in.close();
+ if (mySocket != null)
+ mySocket.close();
+ }
+
+ private void displayMenu()
+ {
+ System.out.println("\nBankAppClientTeller");
+ System.out.println("----------------");
+ System.out.println("1. Login");
+ System.out.println("2. Logout");
+ System.out.println("3. Deposit");
+ System.out.println("4. Withdraw");
+ System.out.println("5. Check Balance");
+ System.out.println("6. Open Account");
+ System.out.println("7. Close Account");
+ System.out.println("8. Modify Account");
+ System.out.println("9. Check Account Info");
+ System.out.println("0. Exit\n");
+ System.out.print("Enter Choice: ");
+ return;
+ }
+
+ private void startClient()
+ throws IOException
+ {
+ int clientQuit = 0;
+ int status = SUCCESS;
+ int isConnected = 0;
+ boolean loggedIn = false;
+ BufferedReader local_in = new BufferedReader(new InputStreamReader(System.in));
+ while (clientQuit == 0)
+ {
+ if (!loggedIn)
+ establishConnection();
+ isConnected = 1;
+ while (isConnected == 1)
+ {
+ displayMenu();
+ String input = local_in.readLine();
+ int selection = Integer.parseInt(input);
+ String response;
+ switch (selection)
+ {
+ case 0:
+ System.out.println("Exitting...");
+ out.println("EXIT");
+ System.exit(0);
+ break;
+ case 1:
+ System.out.println("Login");
+ out.println("LOGIN");
+ response = in.readLine();
+ if (response.equals("OK"))
+ {
+ System.out.print("Enter account number: ");
+ String accountNumber = local_in.readLine();
+ System.out.print("Enter PIN: ");
+ String pinNumber = local_in.readLine();
+ out.println(accountNumber);
+ out.println(pinNumber);
+ response = in.readLine();
+ if (response.equals(accountNumber))
+ {
+ System.out.println("Login Successful! Account: " + response);
+ loggedIn = true;
+ }
+ else
+ {
+ System.out.println(response);
+ }
+ }
+ else
+ {
+ System.out.println(response);
+ }
+ break;
+ case 2:
+ System.out.println("Logout");
+ out.println("LOGOUT");
+ response = in.readLine();
+ if (response.equals("OK"))
+ {
+ response = in.readLine();
+ System.out.println("Logout Successful! Account: " + response);
+ }
+ else
+ {
+ System.out.println(response);
+ }
+ break;
+ case 3:
+ System.out.println("Deposit");
+ out.println("TELLERDEPOSIT");
+ response = in.readLine();
+ if (response.equals("OK"))
+ {
+ System.out.print("Enter Account Number: ");
+ String accNum = local_in.readLine();
+ out.println(accNum);
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ break;
+ }
+ System.out.print("Enter Deposit Amount: ");
+ String depAmount = local_in.readLine();
+ out.println(depAmount);
+ response = in.readLine();
+ if (response.equals("OK"))
+ {
+ response = in.readLine();
+ }
+ }
+ System.out.println(response);
+ break;
+ case 4:
+ System.out.println("Withdraw");
+ out.println("TELLERWITHDRAW");
+ response = in.readLine();
+ if (response.equals("OK"))
+ {
+ System.out.print("Enter Account Number: ");
+ String accNum = local_in.readLine();
+ out.println(accNum);
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ break;
+ }
+ System.out.print("Enter Withdrawal Amount: ");
+ String wdAmount = local_in.readLine();
+ out.println(wdAmount);
+ response = in.readLine();
+ if (response.equals("OK"))
+ {
+ response = in.readLine();
+ }
+ }
+ System.out.println(response);
+ break;
+ case 5:
+ System.out.println("Check Balance");
+ out.println("TELLERCHECK");
+ response = in.readLine();
+ if (response.equals("OK"))
+ {
+ System.out.print("Enter Account Number: ");
+ String accNum = local_in.readLine();
+ out.println(accNum);
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ break;
+ }
+ response = in.readLine();
+ }
+ System.out.println(response);
+ break;
+ case 6:
+ System.out.println("Account Open");
+ out.println("TELLEROPEN");
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ break;
+ }
+ System.out.print("Enter Account Number: ");
+ out.println(local_in.readLine());
+ System.out.print("Enter First Name: ");
+ out.println(local_in.readLine());
+ System.out.print("Enter Middle Name: ");
+ out.println(local_in.readLine());
+ System.out.print("Enter Last Name: ");
+ out.println(local_in.readLine());
+ System.out.print("Enter Account Type: ");
+ out.println(local_in.readLine());
+ System.out.print("Enter Initial Balance: ");
+ out.println(local_in.readLine());
+ System.out.print("Enter PIN: ");
+ out.println(local_in.readLine());
+ response = in.readLine();
+ if (response.equals("OK"))
+ response = in.readLine();
+ System.out.println(response);
+ break;
+ case 7:
+ System.out.println("Account Close");
+ out.println("TELLERCLOSE");
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ break;
+ }
+ System.out.print("Enter Account Number: ");
+ out.println(local_in.readLine());
+ response = in.readLine();
+ if (response.equals("OK"))
+ response = in.readLine();
+ System.out.println(response);
+ break;
+ case 8:
+ System.out.println("Modify Account");
+ out.println("TELLERMODIFY");
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ break;
+ }
+ System.out.print("Enter Account Number: ");
+ String accNum = local_in.readLine();
+ out.println(accNum);
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ break;
+ }
+ int done = 0;
+ while (done == 0)
+ {
+ System.out.println("1. Change Name");
+ System.out.println("2. Change Type");
+ System.out.println("3. Change PIN");
+ System.out.println("4. Change Balance");
+ System.out.println("5. Done\n");
+ System.out.print("Enter Choice: ");
+ int choice = Integer.parseInt(local_in.readLine());
+ switch (choice)
+ {
+ case 1:
+ out.println("CHANGENAME");
+ System.out.print("Enter New First Name: ");
+ out.println(local_in.readLine());
+ System.out.print("Enter New Middle Name: ");
+ out.println(local_in.readLine());
+ System.out.print("Enter New Last Name: ");
+ out.println(local_in.readLine());
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ }
+ break;
+ case 2:
+ out.println("CHANGETYPE");
+ System.out.print("Enter New Account Type: ");
+ out.println(local_in.readLine());
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ }
+ break;
+ case 3:
+ out.println("CHANGEPIN");
+ System.out.print("Enter New PIN: ");
+ out.println(local_in.readLine());
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ }
+ break;
+ case 4:
+ out.println("CHANGEBALANCE");
+ System.out.print("Enter New Balance: ");
+ out.println(local_in.readLine());
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ }
+ break;
+ case 5:
+ done = 1;
+ out.println("DONE");
+ break;
+ default:
+ System.out.println("Invalid selection");
+ break;
+ }
+ }
+ response = in.readLine();
+ System.out.println(response);
+ break;
+ case 9:
+ System.out.println("View Account");
+ out.println("TELLERVIEW");
+ response = in.readLine();
+ if (!response.equals("OK"))
+ {
+ System.out.println(response);
+ break;
+ }
+ System.out.print("Enter Account Number: ");
+ String accNumber = local_in.readLine();
+ out.println(accNumber);
+ response = in.readLine();
+ if (response.equals("OK"))
+ response = in.readLine();
+ System.out.println(response);
+ break;
+ default:
+ System.out.println("Invalid Selection");
+ break;
+ }
+ System.out.println("Press Enter to Continue...");
+ local_in.readLine();
+ }
+ }
+ }
+
+ public static void main(String [] args)
+ throws IOException
+ {
+ System.out.println("BankAppClientTeller in Java");
+ BankAppClientTeller client = new BankAppClientTeller();
+ client.startClient();
+ }
+}
--- /dev/null
+// Bank App in Java
+
+// Author: Danish Lakhani
+
+// BankAppServer - Bank Application Server that services one client at a time
+
+import java.io.*;
+import java.net.*;
+import java.util.*;
+
+class BankAppServer
+{
+ static int SUCCESS = 0;
+ static int ERROR = 1;
+
+ static int LOGIN_ACCOUNT = 1;
+ static int LOGIN_PIN = 2;
+
+ static int ACCOUNT_SAVINGS = 1;
+ static int ACCOUNT_CHECKING = 2;
+ static int ACCOUNT_TELLER = 3;
+
+ private ServerSocket serverSocket = null;
+ private Socket clientSocket = null;
+ private PrintWriter out = null;
+ private BufferedReader in = null;
+ private static int serverPort = 44444;
+ private AccountDatabase accounts = null;
+
+ private boolean isLoggedIn = false;
+ private Integer activeAccount = 0;
+ private Integer tellerCode = 0;
+
+ public BankAppServer()
+ {
+// initializeServer();
+ }
+
+ private void initializeServer()
+ {
+ //Initialize Database
+ accounts = new AccountDatabase();
+
+ //Initialize Server Socket
+ System.out.print("Creating Server Socket...");
+ try {
+ serverSocket = new ServerSocket(serverPort);
+ } catch (IOException e) {
+ System.out.println("Cannot listen on port " + serverPort);
+ System.exit(-1);
+ }
+ System.out.println("Done");
+ }
+
+ private void establishConnection()
+ throws IOException
+ {
+ System.out.print("Waiting for connection...");
+ try {
+ clientSocket = serverSocket.accept();
+ } catch (IOException e) {
+ System.out.println("Accept failed");
+ System.exit(-1);
+ }
+ out = new PrintWriter(clientSocket.getOutputStream(), true);
+ in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
+ System.out.println("Connection Established!");
+ }
+
+ private int authenticateUser(Integer accountNumber, Integer pin)
+ {
+ if (!accounts.accountExists(accountNumber))
+ return LOGIN_ACCOUNT;
+ if (accounts.getPin(accountNumber) != pin)
+ return LOGIN_PIN;
+ return SUCCESS;
+ }
+
+ private int login()
+ throws IOException
+ {
+ out.println("OK");
+ Integer accountNumber = new Integer(in.readLine());
+ System.out.println("Account number: " + accountNumber);
+ Integer pin = new Integer(in.readLine());
+ System.out.println("PIN: " + pin);
+ System.out.println("Authenticating...");
+ int status = authenticateUser(accountNumber, pin);
+ if (status == SUCCESS)
+ {
+ out.println(accountNumber);
+ isLoggedIn = true;
+ tellerCode = 0;
+ activeAccount = 0;
+ if (accounts.isTeller(accountNumber))
+ tellerCode = accountNumber;
+ else
+ activeAccount = accountNumber;
+ System.out.println("Logged Success");
+ return SUCCESS;
+ }
+ else {
+ if (status == LOGIN_ACCOUNT)
+ out.println("ERROR: login failed: Account " + accountNumber + " does not exist.");
+ else
+ out.println("ERROR: login failed: Incorrect pin.");
+ }
+ System.out.println("Login Failed");
+ return ERROR;
+ }
+
+ private void closeConnection()
+ throws IOException
+ {
+ out.close();
+ in.close();
+ clientSocket.close();
+// serverSocket.close();
+ }
+
+ private void processDeposit(Integer accountNumber) throws IOException
+ {
+ String inVal;
+ if (!accounts.accountExists(accountNumber))
+ {
+ out.println("ERROR: Account " + accountNumber + " not found.");
+ return;
+ }
+
+ out.println("OK");
+
+ //Get Deposit Amount
+ inVal = in.readLine();
+ Double depAmount = new Double(inVal);
+ if (depAmount <= 0)
+ {
+ out.println("ERROR: Negative or zero deposit amount");
+ return;
+ }
+
+ accounts.deposit(accountNumber, depAmount);
+ out.println("OK");
+ out.println("$" + depAmount + " deposited successfully! Account: " + accountNumber + " New Balance: " + accounts.getBalance(accountNumber));
+ return;
+ }
+
+ private void processWithdrawal(Integer accountNumber) throws IOException
+ {
+ String inVal;
+ if (!accounts.accountExists(accountNumber))
+ {
+ out.println("ERROR: Account " + accountNumber + " not found.");
+ return;
+ }
+
+ out.println("OK");
+
+ //Get withdrawal amount
+ inVal = in.readLine();
+ Double wdAmount = new Double(inVal);
+ if (wdAmount <= 0)
+ {
+ out.println("ERROR: Negative or zero withdrawal amount");
+ return;
+ }
+// else if (wdAmount > accounts.getBalance(accountNumber))
+// {
+// out.println("ERROR: Insufficient funds. Balance = " + accounts.getBalance(accountNumber));
+// return;
+// }
+
+ accounts.withdraw(accountNumber, wdAmount);
+ out.println("OK");
+ out.println("$" + wdAmount + " withdrawn successfully! Account: " + accountNumber + " New Balance: " + accounts.getBalance(accountNumber));
+ return;
+ }
+
+ private void processBalanceCheck(Integer accountNumber)
+ {
+ out.println("OK");
+ out.println("Account: " + accountNumber + " Balance: " + accounts.getBalance(accountNumber));
+ return;
+ }
+
+ private void startServer()
+ throws IOException
+ {
+ int serverQuit = 0;
+ int status = SUCCESS;
+ int isConnected = 0;
+ initializeServer();
+ while (serverQuit == 0)
+ {
+ establishConnection();
+ isConnected = 1;
+ accounts.loadDatabase();
+ while (isConnected == 1)
+ {
+ System.out.println("Waiting for request...");
+ // Wait for requests
+ String request = in.readLine();
+ if (request == null)
+ continue;
+
+ System.out.println("Request: " + request);
+
+ // Service requests
+ if (request.equals("EXIT"))
+ {
+ accounts.storeDatabase();
+ isLoggedIn = false;
+ activeAccount = 0;
+ tellerCode = 0;
+ closeConnection();
+ isConnected = 0;
+ continue;
+ }
+
+ if (request.equals("LOGIN"))
+ {
+ if (isLoggedIn)
+ {
+ out.println("ERROR: Already logged in. Please logout.");
+ continue;
+ }
+ status = login();
+ if (status == ERROR)
+ {
+// isConnected = 0;
+ continue;
+ }
+ }
+
+ if (!isLoggedIn)
+ {
+ out.println("ERROR: Not logged in");
+ continue;
+ }
+
+ if (request.equals("LOGOUT"))
+ {
+ out.println("OK");
+ if (tellerCode == 0)
+ out.println(activeAccount);
+ else
+ out.println(tellerCode);
+ accounts.storeDatabase();
+ isLoggedIn = false;
+ activeAccount = 0;
+ tellerCode = 0;
+// closeConnection();
+// isConnected = 0;
+ }
+
+ if (request.equals("DEPOSIT"))
+ {
+ processDeposit(activeAccount);
+ }
+
+ if (request.equals("WITHDRAW"))
+ {
+ processWithdrawal(activeAccount);
+ }
+
+ if (request.equals("CHECK"))
+ {
+ processBalanceCheck(activeAccount);
+ }
+
+ if (request.equals("TELLERDEPOSIT"))
+ {
+ if (tellerCode == 0)
+ {
+ out.println("ERROR: Teller not logged in");
+ continue;
+ }
+ out.println("OK");
+ Integer acc = new Integer(in.readLine());
+ processDeposit(acc);
+ }
+
+ if (request.equals("TELLERWITHDRAW"))
+ {
+ if (tellerCode == 0)
+ {
+ out.println("ERROR: Teller not logged in");
+ continue;
+ }
+ out.println("OK");
+ Integer acc = new Integer(in.readLine());
+ processWithdrawal(acc);
+ }
+
+ if (request.equals("TELLERCHECK"))
+ {
+ if (tellerCode == 0)
+ {
+ out.println("ERROR: Teller not logged in");
+ continue;
+ }
+ out.println("OK");
+ Integer acc = new Integer(in.readLine());
+ processBalanceCheck(acc);
+ }
+
+ if (request.equals("TELLEROPEN"))
+ {
+ if (tellerCode == 0)
+ {
+ out.println("ERROR: Teller not logged in");
+ continue;
+ }
+ out.println("OK");
+ Integer accNum = new Integer(in.readLine());
+ String fName = in.readLine();
+ String mName = in.readLine();
+ String lName = in.readLine();
+ Integer accType = new Integer(in.readLine());
+ Double bal = new Double(in.readLine());
+ Integer pNum = new Integer(in.readLine());
+ status = accounts.openAccount(accNum, fName, mName, lName, accType, bal, pNum);
+ if (status == ERROR)
+ {
+ out.println("ERROR: Account " + accNum + " already exists.");
+ continue;
+ }
+ out.println("OK");
+ out.println("Account Number: " + accNum + " " +
+ "Customer Name: " + fName + " " + mName + " " + lName + " " +
+ "Account Type: " + ((accType == ACCOUNT_SAVINGS)?"SAVINGS":(accType == ACCOUNT_CHECKING)?"CHECKING":"TELLER") + " " +
+ "Balance: $" + bal + " " +
+ "PIN: " + pNum + " ");
+ }
+
+ if (request.equals("TELLERCLOSE"))
+ {
+ if (tellerCode == 0)
+ {
+ out.println("ERROR: Teller not logged in");
+ continue;
+ }
+ out.println("OK");
+ Integer accNum = new Integer(in.readLine());
+ status = accounts.closeAccount(accNum);
+ if (status == ERROR)
+ {
+ out.println("ERROR: Account " + accNum + " does not exist.");
+ continue;
+ }
+ out.println("OK");
+ out.println("Account " + accNum + " closed successfully");
+ }
+
+ if (request.equals("TELLERMODIFY"))
+ {
+ if (tellerCode == 0)
+ {
+ out.println("ERROR: Teller not logged in");
+ continue;
+ }
+ out.println("OK");
+ Integer accNum = new Integer(in.readLine());
+ if (!accounts.accountExists(accNum))
+ {
+ out.println("ERROR: Account " + accNum + " does not exist.");
+ continue;
+ }
+ out.println("OK");
+ String inVal;
+ while (!(inVal = in.readLine()).equals("DONE"))
+ {
+ if (inVal.equals("CHANGENAME"))
+ {
+ String fName = in.readLine();
+ String mName = in.readLine();
+ String lName = in.readLine();
+ accounts.modifyName(accNum, fName, mName, lName);
+ out.println("OK");
+ }
+ else if (inVal.equals("CHANGETYPE"))
+ {
+ Integer newType = new Integer(in.readLine());
+ if (newType.intValue() < 1 || newType.intValue() > 3)
+ {
+ out.println("ERROR: Invalid account type: " + newType + ". Must be 1-3.");
+ continue;
+ }
+ accounts.modifyType(accNum, newType);
+ out.println("OK");
+ }
+ else if (inVal.equals("CHANGEPIN"))
+ {
+ Integer newPin = new Integer(in.readLine());
+ if ((newPin < 0) || (newPin > 9999))
+ {
+ out.println("ERROR: Invalid pin " + newPin + ". Must be 0000-9999.");
+ continue;
+ }
+ accounts.modifyPin(accNum, newPin);
+ out.println("OK");
+ }
+ else if (inVal.equals("CHANGEBALANCE"))
+ {
+ Double newBal = new Double(in.readLine());
+ accounts.modifyBalance(accNum, newBal);
+ out.println("OK");
+ }
+ }
+ out.println("Account Number: " + accNum + " " +
+ "Customer Name: " + accounts.nameString(accNum) + " " +
+ "Account Type: " + accounts.typeString(accNum) + " " +
+ "Balance: $" + accounts.getBalance(accNum) + " " +
+ "PIN: " + accounts.getPin(accNum) + " ");
+ }
+
+ if (request.equals("TELLERVIEW"))
+ {
+ if (tellerCode == 0)
+ {
+ out.println("ERROR: Teller not logged in");
+ continue;
+ }
+ out.println("OK");
+ Integer accNum = new Integer(in.readLine());
+ if (!accounts.accountExists(accNum))
+ {
+ out.println("ERROR: Account " + accNum + " does not exist.");
+ continue;
+ }
+ out.println("OK");
+ out.println("Account Number: " + accNum + " " +
+ "Customer Name: " + accounts.nameString(accNum) + " " +
+ "Account Type: " + accounts.typeString(accNum) + " " +
+ "Balance: $" + accounts.getBalance(accNum) + " " +
+ "PIN: " + accounts.getPin(accNum) + " ");
+ }
+ }
+ }
+ }
+
+ public static void main(String [] args)
+ throws IOException
+ {
+ System.out.println("BankAppServer in Java");
+ BankAppServer server = new BankAppServer();
+ server.startServer();
+ }
+}
+
+class AccountEntry
+{
+ Integer accountNumber;
+ String firstName;
+ String middleName;
+ String lastName;
+ Integer accountType;
+ Double balance;
+ Integer pin;
+
+ public AccountEntry(Integer accNum, String fName, String mName, String lName, Integer accType, Double bal, Integer pNum)
+ {
+ accountNumber = accNum;
+ firstName = fName;
+ middleName = mName;
+ lastName = lName;
+ accountType = accType;
+ balance = bal;
+ pin = pNum;
+ }
+}
+
+
+class AccountDatabase
+{
+ static int ACCOUNT_SAVINGS = 1;
+ static int ACCOUNT_CHECKING = 2;
+ static int ACCOUNT_TELLER = 3;
+ static int SUCCESS = 0;
+ static int ERROR = 1;
+
+ static String dbfilename = "accts.txt";
+
+ Vector<AccountEntry> entries = null;
+
+ public AccountDatabase()
+ {
+ entries = new Vector<AccountEntry>();
+ }
+
+ public void loadDatabase()
+ {
+ entries.removeAllElements();
+ try {
+ BufferedReader fin = new BufferedReader(new FileReader(dbfilename));
+ String str;
+ while ((str = fin.readLine()) != null)
+ {
+ Integer accNum = new Integer(str);
+ String fName = fin.readLine();
+ String mName = fin.readLine();
+ String lName = fin.readLine();
+ Integer accType = new Integer(fin.readLine());
+ Double bal = new Double(fin.readLine());
+ Integer pNum = new Integer(fin.readLine());
+ AccountEntry newEntry = new AccountEntry(accNum, fName, mName, lName, accType, bal, pNum);
+ entries.add(newEntry);
+ }
+ fin.close();
+ } catch (IOException e) {
+ System.out.println("Cannot open database file");
+ System.exit(-1);
+ }
+ printAccounts();
+ }
+
+ public void storeDatabase()
+ {
+ try {
+ BufferedWriter fout = new BufferedWriter(new FileWriter(dbfilename));
+ for (int i = 0; i < entries.size(); i++)
+ {
+ AccountEntry acc = (AccountEntry)entries.elementAt(i);
+ fout.write(acc.accountNumber.toString());
+ fout.newLine();
+ fout.write(acc.firstName);
+ fout.newLine();
+ fout.write(acc.middleName);
+ fout.newLine();
+ fout.write(acc.lastName);
+ fout.newLine();
+ fout.write(acc.accountType.toString());
+ fout.newLine();
+ fout.write(acc.balance.toString());
+ fout.newLine();
+ fout.write(acc.pin.toString());
+ fout.newLine();
+ }
+ fout.close();
+ } catch (IOException e) {
+ System.out.println("Cannot write to database file");
+ System.exit(-1);
+ }
+ }
+
+ public AccountEntry getAccount(Integer accNum)
+ {
+ for (int i = 0; i < entries.size(); i++)
+ {
+ AccountEntry acc = (AccountEntry)entries.elementAt(i);
+ if (acc.accountNumber.equals(accNum))
+ return acc;
+ }
+ return null;
+ }
+
+ public void deposit(Integer accNum, Double amount)
+ {
+ AccountEntry acc = getAccount(accNum);
+ acc.balance += amount;
+ }
+
+ public void withdraw(Integer accNum, Double amount)
+ {
+ AccountEntry acc = getAccount(accNum);
+ acc.balance -= amount;
+ }
+
+ public Double getBalance(Integer accNum)
+ {
+ AccountEntry acc = getAccount(accNum);
+ return acc.balance;
+ }
+
+ public int getPin(Integer accNum)
+ {
+ AccountEntry acc = getAccount(accNum);
+ if (acc != null)
+ return acc.pin.intValue();
+ return -1;
+ }
+
+ public boolean accountExists(Integer accNum)
+ {
+ AccountEntry acc = getAccount(accNum);
+ if (acc != null)
+ return true;
+ return false;
+ }
+
+ public boolean isTeller(Integer accNum)
+ {
+ AccountEntry acc = getAccount(accNum);
+ if (acc.accountType.equals(ACCOUNT_TELLER))
+ return true;
+ return false;
+ }
+
+ public Integer openAccount(Integer accNum, String fName, String mName, String lName, Integer accType, Double bal, Integer pNum)
+ {
+ if (accountExists(accNum))
+ return ERROR;
+ AccountEntry acc = new AccountEntry(accNum, fName, mName, lName, accType, bal, pNum);
+ entries.add(acc);
+ return SUCCESS;
+ }
+
+ public Integer closeAccount(Integer accNum)
+ {
+ if (accountExists(accNum))
+ {
+ AccountEntry acc = getAccount(accNum);
+ entries.remove(acc);
+ return SUCCESS;
+ }
+ else
+ return ERROR;
+ }
+
+ public String nameString(Integer accNum)
+ {
+ AccountEntry acc = getAccount(accNum);
+ if (acc != null)
+ {
+ return (acc.firstName + " " + acc.middleName + " " + acc.lastName);
+ }
+ return "";
+ }
+
+ public String typeString(Integer accNum)
+ {
+ AccountEntry acc = getAccount(accNum);
+ if (acc != null)
+ {
+ return ((acc.accountType == ACCOUNT_SAVINGS)?"SAVINGS":(acc.accountType == ACCOUNT_CHECKING)?"CHECKING":"TELLER");
+ }
+ return "";
+ }
+
+ public void modifyName(Integer accNum, String fName, String mName, String lName)
+ {
+ AccountEntry acc = getAccount(accNum);
+ if (acc != null)
+ {
+ acc.firstName = fName;
+ acc.middleName = mName;
+ acc.lastName = lName;
+ }
+ return;
+ }
+
+ public void modifyType(Integer accNum, Integer newType)
+ {
+ AccountEntry acc = getAccount(accNum);
+ if (acc != null)
+ {
+ acc.accountType = newType;
+ }
+ return;
+ }
+
+ public void modifyPin(Integer accNum, Integer newPin)
+ {
+ AccountEntry acc = getAccount(accNum);
+ if (acc != null)
+ {
+ acc.pin = newPin;
+ }
+ return;
+ }
+
+ public void modifyBalance(Integer accNum, Double newBal)
+ {
+ AccountEntry acc = getAccount(accNum);
+ if (acc != null)
+ {
+ acc.balance = newBal;
+ }
+ return;
+ }
+
+ public void printAccounts()
+ {
+ System.out.println("entries.size = " + entries.size());
+ for (int i = 0; i < entries.size(); i++)
+ {
+ System.out.println("Entry " + i);
+ AccountEntry acc = entries.elementAt(i);
+ System.out.println("1 " + acc.accountNumber.toString());
+ System.out.println("2 " + acc.firstName);
+ System.out.println("3 " + acc.middleName);
+ System.out.println("4 " + acc.lastName);
+ System.out.println("5 " + acc.accountType.toString());
+ System.out.println("6 " + acc.balance.toString());
+ System.out.println("7 " + acc.pin.toString());
+ }
+ }
+}
--- /dev/null
+// Bank App in Java
+
+// Author: Danish Lakhani
+
+import java.io.*;
+import java.net.*;
+
+class BankAppTestClient
+{
+ public static void main(String [] args)
+ throws IOException
+ {
+ BufferedReader local_in = new BufferedReader(new InputStreamReader(System.in));
+ String sendline;
+
+ System.out.println("Client");
+
+ sendline = local_in.readLine();
+if (sendline == null)
+ sendline = "localhost";
+ System.out.println("Connecting to server...");
+ Socket mySocket = new Socket(sendline, 8000);
+
+ System.out.println("Connected!!");
+
+ PrintWriter out = new PrintWriter(mySocket.getOutputStream(), true);
+ BufferedReader in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
+
+
+
+ while (true)
+ {
+ System.out.print("Send: ");
+ sendline = local_in.readLine();
+
+ if (!sendline.equals("no"))
+ {
+ out.println(sendline);
+ }
+ else
+ {
+ System.out.print("Reading: ");
+ String inString = in.readLine();
+ System.out.println(inString);
+ }
+ }
+ }
+}
--- /dev/null
+1111
+Danish
+Salim
+Lakhani
+1
+2000.0
+1234
+1000
+Danish
+Teller
+Lakhani
+3
+0.0
+2000
--- /dev/null
+public class Board {
+ // TicTacToe Board flags
+ flag init;
+
+ int[][] board;
+
+ int winningplayer;
+
+ public Board() {
+ winningplayer = -1;
+ board = new int[3][3];
+ for (int i = 0; i < 3; i++)
+ for (int j = 0; j < 3; j++)
+ board[i][j] = 0;
+ }
+
+ public int makeMove(int row, int col) {
+ if (boardFull() == 1) {
+ winningplayer = 0;
+ return 2;
+ }
+ if (board[row][col] != 0) { // Space taken
+ return -1;
+ }
+ else {
+ board[row][col] = 1;
+ if (checkForWin(1) == 1) { // Check if player won
+ winningplayer = 1;
+ return 2;
+ }
+ // Computer makes move
+ if (computerMakeMove() == 1) { // If made move successful
+ if (checkForWin(2) == 1) { // Check if computer won
+ winningplayer = 2;
+ return 2;
+ }
+ }
+ else { // Board full, no winner
+ winningplayer = 0;
+ return 2;
+ }
+ }
+ return 1;
+ }
+
+ public int boardFull() {
+ for (int i = 0; i < 3; i++)
+ for (int j = 0; j < 3; j++)
+ if (board[i][j] == 0)
+ return 0;
+ return 1;
+ }
+
+ public int computerMakeMove() {
+ for (int i = 0; i < 3; i++)
+ for (int j = 0; j < 3; j++)
+ if (board[i][j] == 0) {
+ board[i][j] = 2;
+ return 1;
+ }
+ return 0;
+ }
+
+ public int checkForWin(int p) {
+ // Add logic for checking if player p wins
+ // Horiz
+
+ if ((board[0][0] == p) && (board[0][1] == p) && (board[0][2] == p) ||
+ (board[1][0] == p) && (board[1][1] == p) && (board[1][2] == p) ||
+ (board[2][0] == p) && (board[2][1] == p) && (board[2][2] == p)) {
+ return 1;
+ }
+
+ // Vert
+ if ((board[0][0] == p) && (board[1][0] == p) && (board[2][0] == p) ||
+ (board[0][1] == p) && (board[1][1] == p) && (board[2][1] == p) ||
+ (board[0][2] == p) && (board[1][2] == p) && (board[2][2] == p)) {
+ return 1;
+ }
+
+ //Diag
+ if ((board[0][0] == p) && (board[1][1] == p) && (board[2][2] == p) ||
+ (board[0][2] == p) && (board[1][1] == p) && (board[2][0] == p)) {
+ return 1;
+ }
+
+ return 0;
+ }
+
+ public int winner() {
+ return winningplayer;
+ }
+}
--- /dev/null
+/* Startup object is generated with the initialstate flag set by the
+ * system to start the computation up */
+
+// Create ServerSocket
+task Startup(StartupObject s {initialstate}) {
+ System.printString("TTT Server Starting...\n");
+ ServerSocket ss = new ServerSocket(8000);
+ System.printString("Creating ServerSocket\n");
+ Board tttBoard = new Board() {init};
+ taskexit(s {!initialstate}); // Turn off initial state flag
+}
+
+//Listen for a request and accept request
+task AcceptConnection(ServerSocket ss{SocketPending}) {
+ System.printString("Waiting for connection...\n");
+ TTTServerSocket ttts = new TTTServerSocket() {TTTSInitialize};
+ System.printString("Calling accept...\n");
+ ss.accept(ttts);
+ System.printString("Connected...\n");
+}
+
+// Process incoming requests
+task ProcessRequest(TTTServerSocket ttts{IOPending && TTTSInitialize}) {
+ System.printString("Request received...");
+ int action = ttts.receive();
+ if (action == 1) { // Make move
+ taskexit(ttts {MakeMove});
+ }
+ else { // Send Error
+ taskexit(ttts {SendError});
+ }
+}
+
+task ProcessMove(TTTServerSocket ttts{MakeMove}, Board tttBoard{init}) {
+ System.printString("Processing player's move...");
+ int result = tttBoard.makeMove(ttts.getRow(), ttts.getCol());
+ if (result == 1) { //Move made, send board display
+ taskexit(ttts {!MakeMove, SendBoard});
+ }
+ else if (result == 2) { //Move made, game over
+ taskexit(ttts {!MakeMove, SendDone});
+ }
+ else {// Error
+ taskexit(ttts {!MakeMove, SendError});
+ }
+}
+
+task SendBoardDisplay(TTTServerSocket ttts{SendBoard}, Board tttBoard{init}) {
+ ttts.sendBoardDisplay(tttBoard);
+}
+
+task GameOver(TTTServerSocket ttts{SendDone}, Board tttBoard{init}) {
+ ttts.sendDone(tttBoard.winner());
+}
+
+task SendErrorMessage(TTTServerSocket ttts{SendError}, Board tttBoard{init}) {
+ ttts.sendError();
+}
--- /dev/null
+public class TTTServerSocket extends Socket {
+ // TTTServerSocket flags
+ flag TTTSInitialize;
+
+ flag MakeMove;
+ flag SendError;
+ flag SendBoard;
+ flag SendDone;
+
+ String request;
+ int row, col;
+
+ //Constructor
+ public TTTServerSocket(){
+ System.printString("Constructing TTTServerSocket....\n");
+ }
+
+ public int receive()
+ {
+ byte b1[] = new byte[1024];
+ read(b1);
+ request = new String(b1);
+ System.printString("request: ");
+ System.printString(request);
+ if (parseTransaction() == 1) {
+ return 1;
+ }
+ return 0;
+ }
+
+ // Parse request
+ public int parseTransaction(){
+ int start = request.indexOf('_');
+ String s = request.subString(start+1);
+//_move:3:3
+ if (s.startsWith("move")==true){
+ //Get row
+ int i1 = s.indexOf(':');
+ String rowStr = new String(s.subString(i1+1, i1+2));
+ row = Integer.parseInt(rowStr);
+
+ //Get col
+ String s2 = new String(s.subString(i1+2));
+ int i2 = s2.indexOf(':');
+ String colStr = new String(s.subString(i2+1, i2+2));
+ col = Integer.parseInt(colStr);
+ return 1;
+
+ }
+ // Error transaction
+ return -1;
+ }
+
+ public int getRow(){
+ return row;
+ }
+ public int getCol(){
+ return col;
+ }
+
+ public void sendBoardDisplay(Board theBoard) {
+ StringBuffer line1 = new String ("display_");
+
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
+ if (theBoard.board[i][j] == 1)
+ line1.append("X");
+ else if (theBoard.board[i][j] == 2)
+ line1.append("O");
+ else
+ line1.append("-");
+ }
+ line1.append("_");
+ }
+ String towrite = new String(line1);
+ write(towrite.getBytes());
+ return;
+ }
+
+ public void sendDone(int winner) {
+ StringBuffer line1 = new String ("done_");
+ if (winner == 0)
+ line1.append("tie");
+ else if (winner == 1)
+ line1.append("player");
+ else
+ line1.append("computer");
+
+ String towrite = new String(line1);
+ write(towrite.getBytes());
+ return;
+ }
+
+ public void sendError() {
+ StringBuffer line1 = new String ("error_wrongmove");
+
+ String towrite = new String(line1);
+ write(towrite.getBytes());
+ return;
+ }
+}
--- /dev/null
+import java.net.*;\r
+import java.io.*;\r
+\r
+public class TTTServer\r
+{\r
+ //the tictactoe game board\r
+ //2d 3x3 char array\r
+ private static char[][] board;\r
+ //keeps track of how many turns have past\r
+ private static int numOfTurns;\r
+ //ints used to store the location of the cell the user will input\r
+ private static int row;\r
+ private static int col;\r
+ private static boolean notDone;\r
+ \r
+ private static void resetGame()\r
+ {\r
+ numOfTurns = 0;\r
+ row = 0;\r
+ col = 0;\r
+ \r
+ for(int i = 0; i < 3; i++)\r
+ {\r
+ for(int j = 0; j < 3; j++)\r
+ {\r
+ board[i][j] = ' ';\r
+ }\r
+ }\r
+ }\r
+ \r
+ private static void displayBoard()\r
+ {\r
+ System.out.println("--------------------");\r
+ System.out.println("[R,C][ 1 ][ 2 ][ 3 ]");\r
+ System.out.println("--------------------");\r
+ System.out.println("[ 1 ]| " + board[0][0] + " | " + board[0][1] +\r
+ " | " + board[0][2] + " | ");\r
+ System.out.println("--------------------");\r
+ System.out.println("[ 2 ]| " + board[1][0] + " | " + board[1][1] +\r
+ " | " + board[1][2] + " | ");\r
+ System.out.println("--------------------");\r
+ System.out.println("[ 3 ]| " + board[2][0] + " | " + board[2][1] +\r
+ " | " + board[2][2] + " | ");\r
+ System.out.println("--------------------"); \r
+ }\r
+ \r
+ //put the move on the board and update numOfTurns\r
+ private static void markMove(char xo)\r
+ {\r
+ board[row - 1][col - 1] = xo;\r
+ numOfTurns++;\r
+ }\r
+ \r
+ //check for a winner or a tie\r
+ //true == winner or tie\r
+ private static boolean checkWinner(char xo)\r
+ {\r
+ //horizontal win\r
+ if(board[0][0] == xo && board[0][0] == board[0][1] &&\r
+ board[0][1] == board[0][2])\r
+ {\r
+ System.out.println(xo + " is the winner!");\r
+ return true;\r
+ }\r
+ //horizontal win\r
+ else if(board[1][0] == xo && board[1][0] == board[1][1] &&\r
+ board[1][1] == board[1][2])\r
+ {\r
+ System.out.println(xo + " is the winner!");\r
+ return true;\r
+ }\r
+ //horizontal win\r
+ else if(board[2][0] == xo && board[2][0] == board[2][1] &&\r
+ board[2][1] == board[2][2])\r
+ {\r
+ System.out.println(xo + " is the winner!");\r
+ return true;\r
+ } \r
+ //vertial win\r
+ else if(board[0][0] == xo && board[0][0] == board[1][0] &&\r
+ board[1][0] == board[2][0])\r
+ {\r
+ System.out.println(xo + " is the winner!");\r
+ return true;\r
+ }\r
+ //vertial win\r
+ else if(board[0][1] == xo && board[0][1] == board[1][1] &&\r
+ board[1][1] == board[2][1])\r
+ {\r
+ System.out.println(xo + " is the winner!");\r
+ return true;\r
+ }\r
+ //vertial win\r
+ else if(board[0][2] == xo && board[0][2] == board[1][2] &&\r
+ board[1][2] == board[2][2])\r
+ {\r
+ System.out.println(xo + " is the winner!");\r
+ return true;\r
+ }\r
+ //diagonal win\r
+ else if(board[0][0] == xo && board[0][0] == board[1][1] &&\r
+ board[1][1] == board[2][2])\r
+ {\r
+ System.out.println(xo + " is the winner!");\r
+ return true;\r
+ }\r
+ //diagonal win\r
+ else if(board[0][2] == xo && board[0][2] == board[1][1] &&\r
+ board[1][1] == board[2][0])\r
+ {\r
+ System.out.println(xo + " is the winner!");\r
+ return true;\r
+ }\r
+ //tie game\r
+ //board is full\r
+ else if(numOfTurns == 9)\r
+ {\r
+ System.out.println("Tie Game!");\r
+ return true; \r
+ }\r
+ //no winner yet\r
+ else\r
+ return false;\r
+ }\r
+ \r
+ //the logic that happens for each turn for X or O\r
+ public static void turnLogic(char xo, int r, int c)\r
+ {\r
+ if(xo == 'X')\r
+ {\r
+ System.out.println("\n" + xo + "'s turn.");\r
+ System.out.println("Please enter your move as two separate integers: ");\r
+ //-1 -1 to quit\r
+ row = readInt();\r
+ col = readInt();\r
+ System.out.println("\nYou entered (" + row + "," + col + ")\n");\r
+ }\r
+ else if(xo == 'O')\r
+ {\r
+ System.out.println("\n" + xo + "'s turn.");\r
+ row = r;\r
+ col = c;\r
+ }\r
+ \r
+ markMove(xo);\r
+ displayBoard();\r
+\r
+ //check for a winner and quit cond.\r
+ if(checkWinner(xo) || (row == -1 && col == -1))\r
+ notDone = false;\r
+ }\r
+ \r
+ public static void main(String[] args)\r
+ { \r
+ //the sockets to be used\r
+ ServerSocket mySocket = null;\r
+ Socket myConnection= null;\r
+ //string that will hold the message to be received and sent\r
+ String myString = null;\r
+ //input buffer\r
+ BufferedReader myInput = null;\r
+ //output buffer\r
+ PrintStream myOutput = null;\r
+ //loop variable\r
+ notDone = true;\r
+ \r
+ board = new char[3][3];\r
+ resetGame();\r
+ \r
+ //start server\r
+ try\r
+ {\r
+ //create new socket\r
+ mySocket = new ServerSocket(8080);\r
+ System.out.println("Server Port: " + mySocket.getLocalPort());\r
+ \r
+ displayBoard();\r
+ \r
+ //accept incoming tcp connection\r
+ myConnection = mySocket.accept();\r
+ \r
+ //create and read the message from the client to the input buffer\r
+ myInput = new BufferedReader(new InputStreamReader(myConnection.getInputStream()));\r
+ \r
+ //create and print the message to the output buffer\r
+ myOutput = new PrintStream(myConnection.getOutputStream());\r
+ \r
+ //loop for nine times at most\r
+ while(numOfTurns != 9 && notDone == true)\r
+ {\r
+ switch(numOfTurns % 2)\r
+ {\r
+ //even case\r
+ case 0: \r
+ turnLogic('X', 0, 0);\r
+ myOutput.println(row + " " + col); \r
+ break;\r
+ \r
+ //odd case\r
+ case 1:\r
+ myString = myInput.readLine(); \r
+ \r
+ //was "quit" received?\r
+ if(myString.equals("quit"))\r
+ {\r
+ notDone = false;\r
+ }\r
+ else\r
+ {\r
+ int r = Integer.parseInt(myString.substring(0, 1));\r
+ int c = Integer.parseInt(myString.substring(2, 3));\r
+ turnLogic('O', r, c);\r
+ }\r
+ break;\r
+ \r
+ //should not happen\r
+ default:\r
+ System.out.println("Program Error!");\r
+ break;\r
+ }\r
+ }\r
+ \r
+ //close buffers\r
+ myInput.close();\r
+ myOutput.close();\r
+ \r
+ //close socket\r
+ myConnection.close();\r
+ }\r
+ catch(IOException e)\r
+ {\r
+ System.err.println(e);\r
+ System.exit(1);\r
+ }\r
+ }\r
+ \r
+ //some good stuff to read user ints, maybe too much?\r
+ public static int readInt() throws NumberFormatException\r
+ {\r
+ String inputString = null;\r
+ inputString = readWord();\r
+ \r
+ return Integer.parseInt(inputString);\r
+ }\r
+\r
+ //read a lot \r
+ public static String readWord()\r
+ {\r
+ String result = "";\r
+ char next;\r
+\r
+ next = readChar();\r
+ while (Character.isWhitespace(next))\r
+ next = readChar();\r
+\r
+ while(!(Character.isWhitespace(next)))\r
+ {\r
+ result = result + next;\r
+ next = readChar();\r
+ }\r
+\r
+ if (next == '\r')\r
+ {\r
+ next = readChar();\r
+ \r
+ if (next != '\n')\r
+ {\r
+ System.err.println("Error.");\r
+ System.exit(1);\r
+ }\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ //read one\r
+ public static char readChar()\r
+ {\r
+ int charAsInt = -1; \r
+ \r
+ try\r
+ {\r
+ charAsInt = System.in.read();\r
+ }\r
+ catch(IOException e)\r
+ {\r
+ System.err.println(e);\r
+ System.exit(1);\r
+ }\r
+\r
+ return (char)charAsInt;\r
+ }\r
+}\r