java Socket exception error Connection reset

335 Views Asked by At

I have an issue with the java socket server, I have an IoT device (client) sending msg(HB) every 1 minute to my server through the socket, when receiving a bigger msg it hangs while reading and an error appears: Connection reset. after this error happened when the client sends a new msg it gives this error: Connection reset by peer: socket write error

server code

 public void run() {
        try {
            ServerSocket server = new ServerSocket(this.port);

            System.out.println("Starting to listen on port " + this.port);
            log.info("UTC Server Start");

            while (true) {
                Socket panel = server.accept();
                System.out.println("accept client  = " + panel.getInetAddress().getHostName());
                new PanelHandler(panel, this.listener).run();
            }
        } catch (IOException ex) {
            System.err.println("Socket server error" + ex.getMessage());
            // restart server
            start();
        }
    }

panel handler class code

public class PanelHandler implements Runnable {

 public PanelHandler(Socket panel) throws IOException {
        this.panel = panel;
        this.in = this.panel.getInputStream();
        this.out = this.panel.getOutputStream();
}

  @Override
    public void run() {

        try {

            this.panel.setKeepAlive(true);

            try {
                handshakePanel();
                readMessage();
                writeAck();

            } catch (Exception ex) {
                System.err.println("Error: " + ex.getMessage());
            }
        } catch (SocketException ex) {
            Logger.getLogger(PanelHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    private void readMessage() throws Exception {
        int count;
        byte[] buffer = new byte[1024];

        count = this.in.read(buffer);

        parse(setReceivedMsg(buffer, count));
    }


    private void writeAck() throws IOException, Exception {
        try {
            Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, this.key);
            byte[] ACK = "ACK\r".getBytes("UTF-8");
            byte[] arr = {0, 0, 0, 0};
            ACK = ByteBuffer.allocate(ACK.length + arr.length).put(ACK).put(arr).array();

            byte[] cipherText = cipher.doFinal(ACK);
  
            this.out.write(cipherText);

        } catch (Exception e) {
            System.err.println("writeAck Error = : " + e.getMessage());
        }

    }
}

0

There are 0 best solutions below