Java写的保持socket长连接客户端代码

本文介绍了一个Java客户端如何实现心跳包发送和接收,以及在连接断开时的自动重连机制。通过一个具体的代码示例,展示了如何使用线程进行定时的心跳发送,并在未收到服务器响应超过一定时间后尝试重新建立连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:https://blog.youkuaiyun.com/u013316901/article/details/78215157

public class Client {
    private Socket socket = null;
    private OutputStream os = null;
    private InputStream is = null;

    public static void main(String[] args) {
        new Client().new SocketThread().start();
    }

    /**
     * 发送心跳包
     */
    public void sendHeartbeat() {
        try {
            String heartbeat = "heart:00001;";
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(10 * 1000);// 10s发送一次心跳
                            os.write(heartbeat.getBytes());
                            os.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class SocketThread extends Thread {

        @Override
        public void run() {
            long startTime = System.currentTimeMillis();
            sendHeartbeat();
            while (true) {
                try {
                    if (socket == null || socket.isClosed()) { 
                        socket = new Socket("localhost", 8080); // 连接socket
                        os = socket.getOutputStream();
                    }
                    Thread.sleep(100);
                    is = socket.getInputStream();
                    int size = is.available();
                    if (size <= 0) {
                        if ((System.currentTimeMillis() - startTime) > 3 * 10 * 1000) { // 如果超过30秒没有收到服务器发回来的信息,说明socket连接可能已经被远程服务器关闭
                            socket.close(); // 这时候可以关闭socket连接
                            startTime = System.currentTimeMillis();
                        }
                        continue;
                    } else {
                        startTime = System.currentTimeMillis();
                    }
                    byte[] resp = new byte[size];
                    is.read(resp);
                    String response = new String(resp, "utf-8");
                    System.out.println(response);
                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        socket.close();
                        is.close();
                        os.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }
}
--------------------- 
作者:veeson1024 
来源:优快云 
原文:https://blog.youkuaiyun.com/u013316901/article/details/78215157 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值