-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNodeClient.java
More file actions
54 lines (41 loc) · 2.19 KB
/
Copy pathNodeClient.java
File metadata and controls
54 lines (41 loc) · 2.19 KB
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
import java.io.*;
import java.net.Socket;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class NodeClient {
private static final String HOST = "localhost";
private static final int PORT = 5001;
private static final int DEFAULT_ORDERS = 10;
public static void main(String[] args) throws IOException, InterruptedException {
String nodeName = args.length > 0 ? args[0] : "Node-?";
int numOrders = args.length > 1 ? Integer.parseInt(args[1]) : DEFAULT_ORDERS;
System.out.printf("[%s] Connecting to %s:%d...%n", nodeName, HOST, PORT);
try (Socket socket = new Socket(HOST, PORT);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream())) {
System.out.printf("[%s] Connected. Sending %,d orders...%n", nodeName, numOrders);
Random random = new Random();
AtomicInteger idCounter = new AtomicInteger(1);
for (int i = 0; i < numOrders; i++) {
int seqId = idCounter.getAndIncrement();
int roll = random.nextInt(10);
Order order;
if (roll < 8) { // 80% BUY/SELL
Order.Side side = (roll < 4) ? Order.Side.BUY : Order.Side.SELL;
double price = 100.0 + (random.nextDouble() * 4);
int qty = 1 + random.nextInt(100);
order = new Order(seqId, side, price, qty, -1);
} else { // 20% CANCEL
int cancelTarget = Math.max(1, seqId - random.nextInt(50));
order = new Order(seqId, Order.Side.CANCEL, 0, 0, cancelTarget);
}
// Simulate network latency (remove for stress testing)
Thread.sleep(random.nextInt(100));
out.writeObject(order);
out.flush();
System.out.printf("[%s] Sent: %s%n", nodeName, order);
}
System.out.printf("[%s] Done sending. Closing connection.%n", nodeName);
// try-with-resources closes socket — server sees EOF, ClientHandler exits
}
}
}