Home>Article>Java> Java determines whether the socket server is disconnected

Java determines whether the socket server is disconnected

王林
王林 Original
2020-01-16 09:18:00 3194browse

Java determines whether the socket server is disconnected

You can use the sendUrgentData method in the socket class. This method will send one byte of data to the output stream. As long as the SO_OOBINLINE attribute of the other party's Socket is not turned on, this byte will be automatically discarded. , and the SO_OOBINLINE attribute is turned off by default.

So, the following piece of code can determine whether the remote end has disconnected:

try{ socket.sendUrgentData(0xFF); }catch(Exception ex){ reconnect(); }

(Free learning video tutorial sharing:java video tutorial)

Use ping to implement:

package com.csdn.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class test { static BufferedReader bufferedReader; public static void main(String[] args) throws IOException { try { Process process = Runtime.getRuntime().exec("ping 192.168.1.104");//判断是否连接的IP; bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String connectionStr = ""; while ((connectionStr = bufferedReader.readLine()) != null) { System.out.println(connectionStr); } } catch (IOException e) { e.printStackTrace(); } finally { bufferedReader.close(); } } }

Note: This method has a serious shortcoming, that is, you can only determine whether the other party is connected to the network, but not whether the client is turned on.

In fact, when sending and receiving information to the client through socket.getoutstream and socket.getinputstream streams, if the socket is not connected, an exception will be thrown. This is why Java requires network programming to be written in inside try, so just write the client exit processing in catch.

Recommended related articles and tutorials:java introductory tutorial

The above is the detailed content of Java determines whether the socket server is disconnected. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn