89 lines
2.8 KiB
Java
89 lines
2.8 KiB
Java
|
import java.io.InputStream;
|
||
|
import java.io.OutputStream;
|
||
|
import java.io.PrintStream;
|
||
|
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();
|
||
|
|
||
|
Socket client_socket;
|
||
|
InputStream client_is;
|
||
|
OutputStream client_os;
|
||
|
InputStream server_is;
|
||
|
OutputStream server_os;
|
||
|
Socket server_socket;
|
||
|
|
||
|
public LoadBalancer(Socket socket) {
|
||
|
this.client_socket = socket;
|
||
|
}
|
||
|
|
||
|
@Override
|
||
|
public void run() {
|
||
|
try {
|
||
|
client_is = this.client_socket.getInputStream();
|
||
|
client_os = this.client_socket.getOutputStream();
|
||
|
|
||
|
// on selectionne un serveur au pif
|
||
|
int id = rand.nextInt(nbHosts);
|
||
|
server_socket = new Socket(hosts[id], ports[id]);
|
||
|
System.out.println("Established connection with server " + id + " : " + server_socket);
|
||
|
|
||
|
server_is = server_socket.getInputStream();
|
||
|
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");
|
||
|
server_os.write(buffer, 0, buffer_length);
|
||
|
System.out.println("Sent the buffer to client");
|
||
|
|
||
|
} catch (Exception e) {
|
||
|
e.printStackTrace();
|
||
|
} finally {
|
||
|
// 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();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static void main(String[] args) {
|
||
|
System.out.println("Début du load balancer");
|
||
|
try {
|
||
|
ServerSocket 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();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|