/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.
 * <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author 田平 create 2021/3/2 9:57
 */
@Slf4j
public class TcpPortUtil {

	private static final int DEFAULT_TIMEOUT_MS = 10000;

	/**
	 * <pre>
	 *     检查tcp端口是否挂死
	 * </pre>
	 *
	 * @param server
	 * @param port
	 * @return
	 */
	public static boolean checkTcpPort(String server, int port) {
		return checkTcpPort(server, port, DEFAULT_TIMEOUT_MS);
	}

	/**
	 * <pre>
	 *     检查tcp端口是否挂死
	 * </pre>
	 *
	 * @param server
	 * @param port
	 * @param timeoutMS
	 * @return
	 */
	public static boolean checkTcpPort(String server, int port, int timeoutMS) {
		boolean healthy = false;
		long start = System.currentTimeMillis();
		long end;
		try (Socket socket = new Socket()) {
			socket.connect(new InetSocketAddress(server, port), timeoutMS);
			healthy = true;
			end = System.currentTimeMillis();
			log.info("Connect to {}:{} connectTimeout:{}ms success,usedTime:{}ms!", server, port, timeoutMS, end - start);
		} catch (Exception e) {
			end = System.currentTimeMillis();
			log.warn("Connect to {}:{} connectTimeout:{}ms failure,usedTime:{}ms!", server, port, timeoutMS, end - start, e);
		}
		return healthy;
	}

	public static void main(String[] args) {
		System.out.println(checkTcpPort("localhost", 8080, 2000));
	}

}
