Java socket断开重连,使用循环,避免递归造成栈溢出

最近使用递归进行socket重连,导致栈溢出,特此记录一下

public class SocketUtil {
    private Socket socket;
    private OutputStream outputStream;
    private InputStream inputStream;
    private boolean isReconnected = true;
    private final ExecutorService mThreadPool;
    private final String ip = "192.168.1.31";
    private final int port = 8899;

    SocketUtil() {
        mThreadPool = Executors.newFixedThreadPool(1);
    }

    public void releaseSocket() {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        outputStream = null;
        inputStream = null;
        socket = null;
    }

    public void sendMsg(final String msg) {
        mThreadPool.execute(() -> {
            if (socket == null) {
                while (socket == null && isReconnected) {
                    try {
                        socket = new Socket();
                        socket.connect(new InetSocketAddress(ip, port), 2000);
                        outputStream = socket.getOutputStream();
                        outputStream.write(msg.getBytes(StandardCharsets.UTF_8));
                        outputStream.flush();
                    } catch (IOException e) {
                        handleConnectionException(e);
                    }
                }
            } else {
                try {
                    outputStream = socket.getOutputStream();
                    outputStream.write(msg.getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                } catch (IOException e) {
                    handleConnectionException(e);
                }
            }
        });
    }

    private void receiveMsg() {
        mThreadPool.execute(() -> {
            while (isReconnected) {
                if (socket == null) {
                    while (socket == null && isReconnected) {
                        try {
                            socket = new Socket();
                            socket.connect(new InetSocketAddress(ip, port), 2000);
                            inputStream = socket.getInputStream();
                            int available = inputStream.available();
                            if (inputStream != null && available > 0) {
                                byte[] buffer = new byte[4096];
                                int len = inputStream.read(buffer);
                                String message = new String(buffer, 0, len, StandardCharsets.UTF_8);
                                System.out.println(message);
                            }
                        } catch (IOException e) {
                            handleConnectionException(e);
                        }
                    }
                } else {
                    try {
                        inputStream = socket.getInputStream();
                        int available = inputStream.available();
                        if (inputStream != null && available > 0) {
                            byte[] buffer = new byte[4096];
                            int len = inputStream.read(buffer);
                            String message = new String(buffer, 0, len, StandardCharsets.UTF_8);
                            System.out.println(message);
                        }
                    } catch (IOException e) {
                        handleConnectionException(e);
                    }
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void handleConnectionException(IOException e) {
        if (e instanceof SocketTimeoutException) {
            System.out.println("连接超时");
            releaseSocket();
        } else if (e instanceof NoRouteToHostException) {
            System.out.println("地址不存在");
            releaseSocket();
        } else if (e instanceof ConnectException) {
            System.out.println("连接异常或被拒绝");
            releaseSocket();
        } else {
            System.out.println("连接断开");
            releaseSocket();
        }
    }

    public static void main(String[] args) {
        SocketUtil util = new SocketUtil();
        util.sendMsg("1111");
        util.receiveMsg();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值