背景
用于测试某些地址是否可以链接成功,或发送消息成功
简单案例
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
public class SocketConnectionTester {
public static void main(String[] args) {
String host = "your.host.address"; // 目标主机地址
int port = 12345; // 目标服务端口
try {
// 创建一个Socket实例并尝试连接到指定地址和端口
Socket socket = new Socket();
socket.setSoTimeout(1000);
socket.setKeepAlive(true);
socket.connect(new InetSocketAddress(host, port), 1000); // 第二个参数是连接超时时间,单位毫秒
socket.sendUrgentData(0xFF);
System.out.println("成功连接到 " + host + ":" + port);
// 如果需要,可以发送或接收数据
// OutputStream outputStream = socket.getOutputStream();
// InputStream inputStream = socket.getInputStream();
// 测试完毕后,关闭Socket连接
socket.close();
} catch (IOException e) {
System.err.println("无法连接到 " + host + ":" + port + ", 原因: " + e.getMessage());
} finally {
try {
socket.close();
} catch (Exception e) {}
}
}
}