TP-intergiciel/TP1/LoadBalancer.java

86 lines
2.8 KiB
Java
Raw Normal View History

2023-04-22 15:35:59 +00:00
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class LoadBalancer extends Thread {
static String hosts[] = { "localhost", "localhost" };
static int ports[] = { 8081, 8082 };
static int nbHosts = 2;
static Random rand = new Random();
static ServerSocket ss;
Socket client_socket;
public LoadBalancer(Socket socket) {
this.client_socket = socket;
}
@Override
public void run() {
try {
InputStream client_is = this.client_socket.getInputStream();
OutputStream client_os = this.client_socket.getOutputStream();
// on selectionne un serveur au pif
int id = rand.nextInt(nbHosts);
Socket server_socket = new Socket(hosts[id], ports[id]);
System.out.println("Established connection with server " + id + " : " + server_socket);
InputStream server_is = server_socket.getInputStream();
OutputStream server_os = server_socket.getOutputStream();
// création du buffer de transfert
byte[] buffer = new byte[1024];
int buffer_length;
// transfère de la requête du client vers le server
buffer_length = client_is.read(buffer);
System.out.println("Received " + buffer + " from client");
server_os.write(buffer, 0, buffer_length);
System.out.println("Sent the buffer to server " + id);
// transfère de la requête du server vers le client
buffer_length = server_is.read(buffer);
System.out.println("Received " + buffer + " from server");
client_os.write(buffer, 0, buffer_length);
System.out.println("Sent the buffer to client");
// fermeture des streams server
server_os.close();
server_is.close();
// fermeture des streams client
client_os.close();
client_is.close();
// fermeture des sockets client et serer
this.client_socket.close();
server_socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
System.out.println("Début du load balancer");
try {
ss = new ServerSocket(8080);
System.out.println("ServerSocket créé");
while (true) {
Socket new_client = ss.accept();
System.out.println("Nouvelle connection: " + new_client);
LoadBalancer ld = new LoadBalancer(new_client);
ld.start();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ss.close();
}
}
}