我是靠谱客的博主 孝顺故事,最近开发中收集的这篇文章主要介绍JAVA完成Socket心跳连接和保持,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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完成Socket心跳连接和保持所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(66)

评论列表共有 0 条评论

立即
投稿
返回
顶部