Search in sources :

Example 1 with Io

use of suite.os.SocketUtil.Io in project suite by stupidsing.

the class LoadBalancer method run.

public void run() throws IOException {
    BooMutable running = BooMutable.true_();
    Thread probe = new Thread(() -> {
        while (running.isTrue()) try {
            List<String> alives1 = new ArrayList<>();
            for (String server : servers) try (Socket socket = new Socket(server, port)) {
                alives1.add(server);
            } catch (SocketException ex) {
            }
            alives = alives1;
            Thread.sleep(500l);
        } catch (Exception ex) {
            LogUtil.error(ex);
        }
    });
    Io io = (is, os) -> {
        int count = counter.getAndIncrement();
        List<String> alives0 = alives;
        String server = alives0.get(count % alives0.size());
        try (Socket socket = new Socket(server, port)) {
            InputStream sis = socket.getInputStream();
            OutputStream sos = socket.getOutputStream();
            List<Thread> threads = List.of(Copy.streamByThread(is, sos), Copy.streamByThread(sis, os));
            Thread_.startJoin(threads);
        }
    };
    try {
        probe.start();
        new SocketUtil().listenIo(port, io);
    } finally {
        running.setFalse();
    }
}
Also used : OutputStream(java.io.OutputStream) Socket(java.net.Socket) SocketUtil(suite.os.SocketUtil) Copy(suite.util.Copy) LogUtil(suite.os.LogUtil) BooMutable(suite.primitive.BooMutable) Thread_(suite.util.Thread_) IOException(java.io.IOException) ArrayList(java.util.ArrayList) SocketException(java.net.SocketException) List(java.util.List) Io(suite.os.SocketUtil.Io) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InputStream(java.io.InputStream) SocketException(java.net.SocketException) Io(suite.os.SocketUtil.Io) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) SocketException(java.net.SocketException) BooMutable(suite.primitive.BooMutable) ArrayList(java.util.ArrayList) List(java.util.List) SocketUtil(suite.os.SocketUtil) Socket(java.net.Socket)

Aggregations

IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 Socket (java.net.Socket)1 SocketException (java.net.SocketException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 LogUtil (suite.os.LogUtil)1 SocketUtil (suite.os.SocketUtil)1 Io (suite.os.SocketUtil.Io)1 BooMutable (suite.primitive.BooMutable)1 Copy (suite.util.Copy)1 Thread_ (suite.util.Thread_)1