java判断tcp正常连接
时间: 2023-08-20 12:04:10 浏览: 132
java程序检查网络连接是否正常
4星 · 用户满意度95%
可以使用Java的Socket类来判断TCP连接是否正常。具体方法如下:
1. 创建Socket对象并指定IP地址和端口号:
```
String ip = "192.168.0.1";
int port = 8080;
Socket socket = new Socket(ip, port);
```
2. 获取Socket的输入输出流:
```
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
```
3. 判断连接是否正常,可以通过往输出流中写入数据并读取输入流中的数据进行确认,例如:
```
String testMessage = "test message";
outputStream.write(testMessage.getBytes());
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
String receivedMessage = new String(buffer, 0, len);
if (receivedMessage.equals(testMessage)) {
System.out.println("TCP connection is normal.");
} else {
System.out.println("TCP connection is abnormal.");
}
```
4. 关闭Socket连接:
```
socket.close();
```
阅读全文