Si modifichi il codice dato, per creare un sistema client-server, in cui client e server comunicano attraverso socket.
public class OperationRequest {
int CCnumber;
int amount;
String request;
OperationRequest(int cc, int val, String what){
CCnumber=cc;
amount=val;
request=what;
}
public int getCCnumber() {
return CCnumber;
}
public int getAmount() {
return amount;
}
public String getRequest() {
return request;
}
}
import java.util.Random;
public class Client {
Bank myBank;
int myAccountNum;
Client(int accNum, Bank b){
myBank = b;
myAccountNum=accNum;
}
public static void main(String[] args) {
Client c=new Client(1, new Bank());
c.exec();
}
public void exec() {
Result r;
String opReq=null;
int howMuch=0;
int times=new Random().nextInt(10);
for(int i=0; i<times; i++) {
howMuch=new Random().nextInt(1000);
if(new Random().nextBoolean()) {
r=myBank.executeOperation(new OperationRequest(1, howMuch, "Deposit"));
} else {
r=myBank.executeOperation(new OperationRequest(1, howMuch, "Withdraw"));
}
System.out.println(r);
}
r=myBank.executeOperation(new OperationRequest(1,2,"Double"));
System.out.println(r);
}
}
public class Bank {
int ccAmounts[]={0,0,0};
public Result executeOperation(OperationRequest op) {
int ccNum=op.getCCnumber();
String opType=op.getRequest();
if(ccNum<0 || ccNum>2) {
return new Result(-1, 0, opType, false);
}
if(opType.equals("Deposit")) {
ccAmounts[ccNum]+=op.getAmount();
return new Result(ccNum, ccAmounts[ccNum], opType, true);
} else if (opType.equals("Withdraw")) {
if(op.getAmount()>ccAmounts[ccNum]) {
return new Result(ccNum, 0, opType, false);
} else {
ccAmounts[ccNum]-=op.getAmount();
return new Result(ccNum, ccAmounts[ccNum],opType,true);
}
} else {
return new Result(ccNum, 0, "unknown", false);
}
}
}
public class Result {
int CCnumber;
int amount;
String opType;
boolean successful;
Result(int cc, int val, String ot, boolean ok){
CCnumber=cc;
amount=val;
opType=ot;
successful=ok;
}
public int getCCnumber() { return CCnumber; }
public int getAmount() { return amount; }
public boolean isSuccessful() { return successful; }
public String getType() { return opType; }
public String toString() {
return "op. "+opType+" on CC num. "+ CCnumber+
(successful?" OK":" KO")+" resulting amount="+amount;
}
}
Bank.java
ClientThread.java
OperationRequest.java
Result.java
MultiClient.java
ClientServerThread.java
ClientThread.java
MultiClient.java
BankServerThread.java
Server.java
BankProxy.java