-
Notifications
You must be signed in to change notification settings - Fork 0
/
DServer.java
89 lines (73 loc) · 2.64 KB
/
DServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* @author Thomas Moroney
*/
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
public class DServer extends Node {
static final int DSERVER_PORT = 50007; // current
static final int CP_PORT = 50006; // cloud provider
static final String CP_NODE = "CP";
InetSocketAddress dstAddress;
double balance = 100;
DServer(int port) {
try {
socket= new DatagramSocket(port);
listener.go();
}
catch(java.lang.Exception e) {e.printStackTrace();}
}
/**
* Assume that incoming packets are request packets.
*/
public void onReceipt(DatagramPacket packet) {
try {
PacketContent content= PacketContent.fromDatagramPacket(packet);
if (content.getType()==PacketContent.TEXTPACKET) {
System.out.println("Received request packet");
TextPacket returnPacket;
String returnString;
TextPacket inPacket = ((TextPacket)content);
String dest = (inPacket.text).substring(3, 6); // isolate return destination
String s = (inPacket.text).substring(6); // remove header
System.out.println("Packet content: "+ s);
System.out.println("Return Destination: " + dest);
dstAddress = new InetSocketAddress(CP_NODE, CP_PORT);
if (s.contains("balance")) { // SEND DATA REQUESTED
System.out.println("Checking Account Balance...");
System.out.println("Balance is: $" + balance);
returnString = dest + "Your current balance is $" + balance + " (Bank Account 1)";
returnPacket = new TextPacket(returnString);
sendReturnPacket(returnPacket);
}
else if (Character.isDigit(s.charAt(0))) {
double deposit = Double.parseDouble(s.trim());
balance = balance + deposit;
returnString = dest + "Deposit was successful - new balance is $" + balance + " (Bank Account 1)";
returnPacket = new TextPacket(returnString);
sendReturnPacket(returnPacket);
}
}
}
catch(Exception e) {e.printStackTrace();}
}
public void sendReturnPacket(TextPacket myPacket) { // change to send byte array packet instead
try {
DatagramPacket returnPacket= myPacket.toDatagramPacket();
returnPacket.setSocketAddress(dstAddress);
socket.send(returnPacket); // Send packet with file name and length
System.out.println("Sent Return Packet\n");
}
catch(Exception e) {e.printStackTrace();}
}
public synchronized void start() throws Exception {
System.out.println("Waiting for contact");
this.wait();
}
public static void main(String[] args) {
try {
(new DServer(DSERVER_PORT)).start();
System.out.println("Program completed");
} catch(java.lang.Exception e) {e.printStackTrace();}
}
}