java 1.8 原生 定时 + telnet检测端口是否连通
修改 hostname 和 port即可
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/*
* 定时,每隔5s执行任务
* 任务:检测 指定hostname 的 port 是否开启
* */
public class TelnetUtil {
/**
* 测试telnet 机器端口的连通性
* @param hostname
* @param port
* @param timeout
* @return
*/
public static boolean telnet(String hostname, int port, int timeout){
Socket socket = new Socket();
boolean isConnected = false;
try {
socket.connect(new InetSocketAddress(hostname, port), timeout); // 建立连接
isConnected = socket.isConnected(); // 通过现有方法查看连通状态
// System.out.println(isConnected); // true为连通
} catch (IOException e) {
System.out.println("false"); // 当连不通时,直接抛异常,异常捕获即可
}finally{
try {
socket.close(); // 关闭连接
} catch (IOException e) {
System.out.println("false");
}
}
return isConnected;
}
public static void main(String[] args) {
// 定时,每隔5s执行一次请求,检测 hostname 的 port 是否开启
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
System.err.println("定时任务执行!!!");
String hostname = "www.baidu.com"; // hostname 可以是主机的 IP 或者 域名
int port = 443;
int timeout = 200;
boolean isConnected = telnet(hostname, port, timeout);
System.out.println("telnet "+ hostname + " " + port + "\n==>isConnected: " + isConnected);
}
};
timer.schedule(task, new Date(),5000);
}
}