java.net.ConnectException: Connection refused processing IDE

hope you doing all well, i m using processing IDE to interact with arduinos chips scattered across the local network, so i did a client server architecture via ethernet, made sure each chips has its own unique and available ip adresse, when i tried to communicate with 3 chips it works well, but the moment i exceed 3 chips simultaniously i m getting a consistant connectException : connection refused from one of the chips, this is the server class i m using in processing :

import java.io.*;
import java.net.*;
import java.util.concurrent.*;

class ServerHandler implements Runnable {
    private ServerSocket server;
    private boolean serverRunning = true;
    private String receivedMessage = null;
    private int port;
    private boolean isConfigserver;
    private ExecutorService clientThreadPool;
    private int clientCounter = 0;

    public ServerHandler(int port, boolean isConfigserver) {
        this.port = port;
        this.isConfigserver = isConfigserver;
        this.clientThreadPool = Executors.newCachedThreadPool();
    }

    @Override
    public void run() {
        try {
            // Create a server socket to listen on the specified port
            server = new ServerSocket(this.port);
            println("Server is running on port : " + this.port);
            
            while (serverRunning) {
                try {     
                    Socket client = server.accept(); // Accept incoming connections
                    clientCounter++;
                    println("Client connected: " + client.getInetAddress() + ", Total clients handled: " + clientCounter);

                    if (!isConfigserver) {
                        // Handle each client connection in a separate thread
                        ClientHandler clientHandler = new ClientHandler(client, selectedMode, Nombre_mesures);
                        clientThreadPool.submit(clientHandler);
                    } else {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
                        String receivedData = reader.readLine();
                        if (receivedData != null) {
                            receivedData = receivedData.trim();
                            println("Received from Arduino about config: " + receivedData);
                            if (receivedData.equals("OK")) {
                                isReady = true;
                                //println("we are ready to go");
                            }
                        }
                        client.close();
                        println("Client connection closed after configuration");
                    }
                } catch (IOException e) {
                    println("Error handling client connection: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            println("Server error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void stopServer() {
        serverRunning = false;
        if (server != null && !server.isClosed()) {
            try {
                server.close();
            } catch (IOException e) {
                println("Error closing server: " + e.getMessage());
                e.printStackTrace();
            }
        }
        clientThreadPool.shutdown();
    }

    private class ClientHandler implements Runnable {
        private Socket client;
        private String selectedMode;
        private int Nombre_mesures;
        private int counter_requete = 0;

        public ClientHandler(Socket client, String selectedMode, int Nombre_mesures) {
            this.client = client;
            this.selectedMode = selectedMode;
            this.Nombre_mesures = Nombre_mesures;
        }

        @Override
        public void run() {
            try {
                println("Handling client: " + client.getInetAddress());
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
                    if (!mode_auto) {
                        while (counter_requete < Nombre_mesures) {
                            String receivedData = reader.readLine();
                            if (receivedData != null) {
                                receivedData = receivedData.trim();
                                println("Received from Arduino: " + receivedData);
                                // extractAndWriteData(receivedData, selectedMode, counter_requete);
                                counter_requete++;
                                println("Current request counter: " + counter_requete);
                            }
                        }
                        counter_requete = 0;
                    } else {
                        if (compteur_auto < Nombre_mesures * combinations1280.size() * gatewayList.size()) {
                            String receivedData = reader.readLine();
                            if (receivedData != null) {
                                receivedData = receivedData.trim();
                                println("Received from Arduino: " + receivedData);
                                extractAndWriteData(receivedData, selectedMode, counter_requete);
                                compteur_auto++;
                                ismesuredone = true;
                                delay(300);
                                // println("Automatic mode counter: " + compteur_auto);
                            }
                        }
                    }
                } catch (IOException e) {
                    println("Error reading client data: " + e.getMessage());
                    e.printStackTrace();
                } finally {
                    try {
                        client.close();
                        println("Client connection closed");
                    } catch (IOException e) {
                        println("Error closing client connection: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                println("Unhandled exception: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    private void delay(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            println("Delay interrupted: " + e.getMessage());
            e.printStackTrace();
        }
    }

}

this server class runs in it own thread as a way to handle response from arduinos chips, as for how a connection is iniatialised, in the main code i do this :

for (int i = 0; i < gatewayList.size(); i++) {
    int index = gatewayList.get(i);
    int[] firstIP = ipAddresses.get(index);
    String adress_GW = firstIP[0] + "." + firstIP[1] + "." + firstIP[2] + "." + firstIP[3];
   // println(adress_GW);

     int retryCount = 0;
    int maxRetries = 5; // Limit the number of retries to avoid infinite loops

   while (!isSent && retryCount < maxRetries) {
        try {
            myClient = new Client(this, adress_GW, 80);
            if (myClient.active()) {
                myClient.write(message);
                isSent = true;
                println("Message sent to " + adress_GW);
            } else {
                println("Client is not active, retrying...");
            }
        } catch (Exception e) {
            println("Exception: " + e.getMessage() + ", retrying... (" + (retryCount + 1) + "/" + maxRetries + ")");
        } finally {
            retryCount++;
            delay(200); // Delay before retrying
        }
    }

    if (!isSent) {
        println("Failed to send message to " + adress_GW + " after " + maxRetries + " retries.");
    }
    isSent = false;
  
      }

where i send a message to each gateway, 3 of the 4 gateway got the message , but the last one consistanly give me this :

java.net.ConnectException: Connection refused: connect
    at java.base/sun.nio.ch.Net.connect0(Native Method)
    at java.base/sun.nio.ch.Net.connect(Net.java:579)
    at java.base/sun.nio.ch.Net.connect(Net.java:568)
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:593)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
    at java.base/java.net.Socket.connect(Socket.java:633)
    at java.base/java.net.Socket.connect(Socket.java:583)
    at java.base/java.net.Socket.<init>(Socket.java:507)
    at java.base/java.net.Socket.<init>(Socket.java:287)
    at processing.net.Client.<init>(Unknown Source)
    at G4P_interface.automatique_window_draw(G4P_interface.java:1335)
    at jdk.internal.reflect.GeneratedMethodAccessor6.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at g4p_controls.GWindow.draw(Unknown Source)
    at g4p_controls.GWindowAWT.draw(Unknown Source)
    at processing.core.PApplet.handleDraw(PApplet.java:2094)
    at processing.awt.PSurfaceAWT$9.callDraw(PSurfaceAWT.java:1386)
    at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:356)

any suggestions why this occur ? why the connection was refused ?

i tried to add connection timeout, retry and further investigate the exception but didn’t find the reason this occured.

New contributor

Hakim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật