JAVA完成Socket心跳连接和保持

该代码段展示了如何使用Java的Socket进行连接、断开、接收和发送消息。它包含两个内部类`KeepThread`用于发送心跳包保持连接,以及`RecvThread`用于接收消息。程序在连接建立或重新连接时启动相关线程,并提供了相应的关闭方法。
摘要由CSDN通过智能技术生成
public class SocketUtil {

	private static final ThreadLocal<Socket> threadConnect = new ThreadLocal<Socket>();

	private static Socket client;

	private static OutputStream outStr = null;

	private static InputStream inStr = null;

	private static Thread tRecv = new Thread(new RecvThread());
	private static Thread tKeep = new Thread(new KeepThread());

	// 连接以及重新连接
	public static void connect(String host, int port) {
		try {
			client = threadConnect.get();
			if (client == null) {
				client = new Socket(host, port);
				threadConnect.set(client);
				tKeep.start();
				System.out.println("========链接开始!========");
			} else if (client.isClosed()) {
				client = new Socket(host, port);
				threadConnect.set(client);
				tRecv = new Thread(new RecvThread());
				tKeep = new Thread(new KeepThread());
				tKeep.start();
				System.out.println("========链接开始!========");
			}
			outStr = client.getOutputStream();
			inStr = client.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 断开连接
	public static void disconnect() {
		try {
			outStr.close();
			inStr.close();
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 接收消息
	public static void receiveMsg() {
		tRecv.start();
	}

	// 发送消息
	public static void sendMsg(String msg) {
		try {
			outStr.write(msg.getBytes());
			outStr.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static class KeepThread implements Runnable {
		public void run() {
			try {
				if (!client.getKeepAlive()) client.setKeepAlive(true);//true,若长时间没有连接则断开
				if (!client.getOOBInline()) client.setOOBInline(true);//true,允许发送紧急数据,不做处理
				while (true) {
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("发送心跳数据包");
					outStr.write("心跳信息".getBytes());
					outStr.flush();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	private static class RecvThread implements Runnable {
		public void run() {
			try {
				System.out.println("==============开始接收数据===============");
				while (true) {
					byte[] b = new byte[1024];
					int r = inStr.read(b);
					if (r > -1) {
						String str = new String(b, 0, r);
						System.out.println(str);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
以下是一个简单的Java socket连接心跳检测代码示例: ```java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class HeartbeatClient { private static final int SERVER_PORT = 8888; private static final String SERVER_IP = "127.0.0.1"; private static final long HEARTBEAT_INTERVAL = 5000; // 心跳间隔时间,单位毫秒 public static void main(String[] args) { Socket socket = null; InputStream in = null; OutputStream out = null; try { socket = new Socket(SERVER_IP, SERVER_PORT); in = socket.getInputStream(); out = socket.getOutputStream(); // 发送心跳包 new Thread(new HeartbeatThread(out)).start(); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) { String message = new String(buffer, 0, len); System.out.println("收到服务器的消息:" + message); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } private static class HeartbeatThread implements Runnable { private OutputStream out; public HeartbeatThread(OutputStream out) { this.out = out; } @Override public void run() { while (true) { try { Thread.sleep(HEARTBEAT_INTERVAL); out.write("heartbeat".getBytes()); out.flush(); System.out.println("发送心跳包"); } catch (InterruptedException | IOException e) { e.printStackTrace(); } } } } } ``` 这个示例中,我们在客户端和服务器之间建立了一个长连接,并且每隔一段时间就发送一个心跳包到服务器,以确保连接不会因为长时间没有数据交换而断开。在线程中,我们使用了`Thread.sleep()`来实现心跳包发送的定时器功能。当连接断开或者发送心跳包失败时,我们可以在`catch`块中重新连接或者做其他处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值