-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnectionServer.java
84 lines (70 loc) · 2.83 KB
/
ConnectionServer.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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class ConnectionServer implements Runnable {
// per connection variables
private Socket mySocket; // connection socket per thread
private String clientName;
private String securitySymbol;
private Server mainServer;
public ConnectionServer(Server mainServer) {
this.mySocket = null; // we will set this later
this.clientName = null;
this.mainServer = mainServer;
// who created me. He should give some interface
}
public boolean handleConnection(Socket socket) {
this.mySocket = socket;
Thread newThread = new Thread(this);
newThread.start();
return true;
}
public void run() { // can not use "throws .." interface is different
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(mySocket.getOutputStream()));
String line;
out.println("Hit Enter to continue");
out.flush();
in.readLine();
out.println("Enter Your Name");
out.flush();
clientName = in.readLine();
out.println("Enter Security Symbol");
out.flush();
securitySymbol = in.readLine();
StockItem si = mainServer.stockDb.getItem(securitySymbol);
if (si == null) {
out.println(-1);
out.flush();
} else {
out.println("stock price is : " + si.getPrice());
out.println("place Your Bid : ");
out.flush();
}
for (line = in.readLine(); line != null && !line.equals("quit"); line = in.readLine()) {
Bid bidItem = new Bid(clientName,Float.parseFloat(line));
if(mainServer.stockDb.placeBid(securitySymbol, bidItem)){
out.println("Bid placed successfully"); // Send the said message
out.println("new Stock price is "+ mainServer.stockDb.getItem(securitySymbol).getPrice()+ ",Place your next Bid");
out.flush(); //
}else{
out.println("Your Bid is too low");
out.println("current Stock price is "+ mainServer.stockDb.getItem(securitySymbol).getPrice()+ ",Place your next Bid");
out.flush();
}
}
// close everything
out.close();
in.close();
this.mySocket.close();
} catch (IOException e) {
System.out.println(e);
}
}
}