-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRR-another version
More file actions
72 lines (61 loc) · 2.29 KB
/
RR-another version
File metadata and controls
72 lines (61 loc) · 2.29 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.io.*;
import java.net.*;
import java.util.LinkedList;
public class RoundRobin {
private static LinkedList<Socket> servers = new LinkedList<>();
private static int serverIndex = 0;
public static void main(String[] args) {
try {
servers.add(new Socket("127.0.0.1", 12345));
servers.add(new Socket("127.0.0.1", 5000));
servers.add(new Socket("127.0.0.1", 4040));
ServerSocket serverSocket = new ServerSocket(5500);
while (true) {
Socket conn = serverSocket.accept();
Socket selected = getNextServer();
processRequest(conn, selected);
}
} catch (IOException e) {
System.err.println(e.getMessage());
} finally {
closeConnections();
}
}
private static synchronized Socket getNextServer() {
serverIndex = (serverIndex + 1) % servers.size();
return servers.get(serverIndex);
}
private static void processRequest(Socket client, Socket server) throws IOException {
try {
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
DataInputStream din = new DataInputStream(in);
DataOutputStream dout = new DataOutputStream(server.getOutputStream());
// Read data from client and send it to server
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
dout.write(buffer, 0, bytesRead);
dout.flush();
}
// Read response from server and send it back to client
buffer = new byte[1024];
bytesRead = server.getInputStream().read(buffer);
if (bytesRead > 0) {
out.write(buffer, 0, bytesRead);
out.flush();
}
} finally {
client.close();
}
}
private static void closeConnections() {
try {
for (Socket server : servers) {
server.close();
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}