|
| 1 | +package lab_06.LoadBalancing; |
| 2 | + |
| 3 | +import java.net.DatagramPacket; |
| 4 | +import java.net.DatagramSocket; |
| 5 | + |
| 6 | +/** * RPCServer_Date */ |
| 7 | +public class LoadBalancer { |
| 8 | + static DatagramSocket serverDatagramSocket; |
| 9 | + static DatagramPacket clientDataPacket; |
| 10 | + static byte buf[]; |
| 11 | + static int s1 = 0, s2 = 5; |
| 12 | + static int s2PORT = 5002, s1PORT = 5001; |
| 13 | + |
| 14 | + public static void main(String[] args) { |
| 15 | + try { |
| 16 | + System.out.println("Load Balancer Daemon up"); |
| 17 | + buf = new byte[1024]; |
| 18 | + serverDatagramSocket = new DatagramSocket(5000); |
| 19 | + clientDataPacket = new DatagramPacket(buf, buf.length); |
| 20 | + while (true) { |
| 21 | + serverDatagramSocket.receive(clientDataPacket); |
| 22 | + int PORTtoSend = 0; |
| 23 | + String currTime = new String(clientDataPacket.getData(), 0, clientDataPacket.getLength()); |
| 24 | + byte[] operationRes = currTime.getBytes(); |
| 25 | + if (s1 > s2) { |
| 26 | + PORTtoSend = s2PORT; |
| 27 | + s2++; |
| 28 | + } else { |
| 29 | + PORTtoSend = s1PORT; |
| 30 | + s1++; |
| 31 | + |
| 32 | + } |
| 33 | + DatagramPacket resDataPacket = new DatagramPacket(operationRes, operationRes.length, |
| 34 | + clientDataPacket.getAddress(), PORTtoSend); |
| 35 | + serverDatagramSocket.send(resDataPacket); |
| 36 | + System.out.println("Sent packet to server at: " + resDataPacket.getPort()); |
| 37 | + } |
| 38 | + } catch (Exception e) { |
| 39 | + e.printStackTrace(); |
| 40 | + } finally { |
| 41 | + serverDatagramSocket.close(); |
| 42 | + } |
| 43 | + } |
| 44 | +} |
0 commit comments